How to build Drools rules in Java dynamically?
How to build Drools rules in Java dynamically instead of providing static drl file?
I开发者_如何学运维 have a set of matching rules defined in xml that I need to parse and be able to reload it in runtime. Is there any way to build Drools rules dynamically? Couldn't find it in the docs.
I agree with Romain's comment - if you have the rules in some declarative form - you could just generate code directly from that - unless there is higher order logic implicit in those rules (unlikely I have found), or perhaps you want to do a one time migration to a rule language out of the XML.
I agree with former answers and comments that rules are ment to be the "static" part. When rules are created dynamically on demand, the usage of a rules engine is questionable. However, there are cases where rules are not provided in form / format that drools can handle out of the box. In such cases programmatical creation of rules during the initialization phase is needed.
These things said, here is how you can add a rule (given as a String) to drools.
public void addRule(String myRuleStatement, String myPackage, RuleBase myRuleBase ) {
PackageBuilder packageBuilder = new PackageBuilder(new Package(myPackage));
packageBuilder.addPackgeFromDrl( new StringReader( myRuleStatement ) );
myRuleBase.addPackage ( packageBuilder.getPackage() );
}
精彩评论