RallyRabbit
RallyRabbit

Reputation: 463

Drools: How to Declare and Assign Global

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???

Upvotes: 5

Views: 8715

Answers (2)

prash
prash

Reputation: 1036

you can also define a function in the DRL

function String getParam(String name){
   return name.equals("x") ? "xValue" : "yValue";
}


.....
/// call it in you rule as below
.....

rule "my rule"
when 
then
  System.out.println(getParam("x"));
end

Upvotes: 0

ankitom
ankitom

Reputation: 130

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.

Upvotes: 6

Related Questions