欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Drools学习笔记】02-动态加载规则

程序员文章站 2022-05-28 11:17:17
...

上一篇Drools简介中的例子将规则写在了drl文件中,我们还可以动态的拼凑我们想要的规则,代码如下:

@Test
public void testKieRuntimeAccess() throws IOException, ClassNotFoundException {
        String str = "";
        str += "package org.drools.compiler.test\n";
        str += "import " + Message.class.getName() + "\n";
        str += "rule \"Hello World\"\n";
        str += "when\n";
        str += "    Message( )\n";
        str += "then\n";
        str += "    System.out.println( drools.getKieRuntime() );\n";
        str += "end\n";

        KieBase kbase = KnowledgeBuilderFactory.newKnowledgeBuilder().add(ResourceFactory.newByteArrayResource(str).getBytes()), ResourceType.DRL);        
        kbase = SerializationHelper.serializeObject( kbase );
        final KieSession ksession = kbase.newKieSession();
        ksession.insert( new Message( "help" ) );
        ksession.fireAllRules();
        ksession.dispose();
}