I want to declare a global variable in a drools rule file (mvel). This is because this global is used in all the rules as a parameter to another function. I could easily pass this string explicitly in every call to the function, but this makes it hard if the string changes.
I thought I could do a:
global String someStr = "some string";
But on compile, I get:
[11,31]: [ERR 107] Line 11:31 mismatched input '=' expecting one of the following tokens: '[package, import, global, declare, function, rule, query]'.
So obviously, I can't assign it this way. Nor do I seem to be able to declare a class and a string in that class to reference through the class.
So I found I could so something that seems silly:
global String someStr;
rule "Initialize"
when
then
someStr = "some string";
end
This seems to work, but, this will log every single time this rule matches (always) to just assign a global.
Is there a better way that I'm missing???
The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
If you intend to use the global variables in multiple . c files, it is better to declare them in . h files. However, if you want to keep the variables like private member data of classes in C++, it will be better to provide access to the global data through functions.
Using globals is a two step process. Declaration and assignment.
Declaration takes place in the rule file.
Assignment takes place at session level in the java code.
In the java code:
List<String> list= new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
KieSession ks = kcontainer.newKieSession("test");
ks.setGlobal("glist", list);
In the drl file:
global java.util.List glist;
Now this glist global variable which has values "a", "b", "c" can be used across all the rules in the drl file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With