How to define variable in side drools and add values to them

妖精的绣舞 提交于 2019-12-25 03:37:14

问题


How to define variable and add values to it inside DRL file that can be used between the rules as a static resource.

I tried to use global keyword but when add I add values to it i will not be effected inside Working Memory as it mentioned in documentation. And in my case i conn't add it from Application side.

Example :

 global java.util.List myList;

function java.util.List initMyList() {
 List list = new ArrayList();
 list.add(1);
 return list;
}

rule "initListRule"
salience 1001
 when
  eval(myList == null)
then
 myList = initMyList();
end

rule "checkIfListIsStillEmptyRule"
 salience 1000
when
 eval(myList != null)
then
 System.out.println("MyList is Not null");
end

as global are not stored in woking memory then myList will be always null as it is not provided from Application side. is there any alternative to define variables and fill them in DRL ?


回答1:


A DRL global is not evaluated dynamically and therefore your rule "checkIfListIsStillEmptyRule" will not fire.

You can do

rule "initListFact"
when
    not List()
then
    insert( new ArrayList() );
end
rule "checkThatThereIsAnEmptyList"
when
    $list: List( size == 0 )
then
    modify( $list ){ add( "something" ) }
end

If you don't need to observe changes of a global you can initialize it in a rule with very high salience. It will be available as a resource but you cannot base rule conditions on its state.

global list myList
rule "initListRule"
salience 9999999999
when
then
    myList = new ArrayList();
end

You can use more than one global:

global List myListOne
global List myListTwo
rule "initListsRule"
salience 9999999999
when
then
    myListOne = new ArrayList();
    myListTwo = new ArrayList();
end

If you need to react to changes, there's no way around facts.

declare NamedList
    name: String
    list: ArrayList
end
rule createListOne
when
    not NamedList( name == "one" )
then
    insert( new NamedList( "one", new ArrayList() ) );
end
rule "checkIfListOneIsStillEmpty"
when
    $nl: NamedList( name == "one", eval( list.size() == 0 ) )
then
    modify( $nl ){vgetList().add( "something" ) }
end


来源:https://stackoverflow.com/questions/33102161/how-to-define-variable-in-side-drools-and-add-values-to-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!