When I'm trying to access the global variable from the drool function I got an exception:
threw exception; nested exception is java.lang.RuntimeException: Unable to get KieModule, Errors Existed: Error Messages: Message [id=1, kieBase=defaultKieBase, level=ERROR, path=insuranceperiod.drl, line=-1, column=0 text=Error importing : 'KieRule.AddString.addString'] Message [id=2, kieBase=defaultKieBase, level=ERROR, path=insuranceperiod.drl, line=15, column=0 text=[ function addStringaddString (line:15): stringList cannot be resolved ]]
the code is below:
List<String> stringList = new ArrayList<>();
droolSession.setGlobal("stringList",stringList)
droolSession.fireAllRules();
global java.util.List stringList;
function void addString(String s){
stringList.add(s);
}
Try to access global variable inside drool function
You cannot access a DRL global from the body of a DRL function.
The rationale is the following: DRL functions are equivalent to Java static
methods. A DRL global can be considered analogous to an instance field (as you can see in your snippet, you set the global value on a Session instance, not a KBase). Similarly to Java, you cannot access instance fields from a static method.
If you tried to define static void addString(String s) {...}
as a static method in Java and then to use it from the RHS, you would have faced similar issue: the definition of the static method do not have scope access to your stringList
instance.
You can always refactor your code to comply with scope visibility and address your need in a different way.