如何在 Drools ResponseObject 中填充地图

How to populate Map in Drools ResponseObject

我在 .drl 中定义了一个对象:

套餐drools.types

declare  ResponsibilityManager 
    @propertyReactive
    internal : java.lang.Long
    attr1 : java.lang.String  
    band : java.lang.Long
    resourceMap : java.util.HashMap

end

我的规则也在 DRL 中定义:

套餐drools.rules

import drools.types.*

rule "Third Test Rule"
    dialect "mvel"
    salience 0
    no-loop true

 when
   $var : ResponsibilityManager( band > 4  )
 then
     modify($var) { attr1 = "hidden";}
     modify($var) { getResourceMap().put("action","edit");}
end

规则编译正确,但是当我从我的 Java 应用程序执行规则时,我在该行中收到“NullPointerException”:

modify($var) { getResourceMap().put("action","edit");}

我可以更新 return "attr1" 属性.

如何更新规则中的地图?

嗯,显然 resourceMap 从未被实例化。

当您创建 ResponsibilityManager 时,您需要确保也在其中创建 resourceMap。

rule "Whatever creates the ResponsibilityManager instance"
when
  // ...
then
  ResponsibilityManager r = new ResponsibilityManager();
  r.setResourceMap(new HashMap());
  // set other fields
  insert(r);
end

然后就可以正常修改了,不会得到空指针

或者您可以完全覆盖该值,例如...

rule "Example with overwrite"
when
  $var: ResponsibilityManager( band > 4, $resources: resourceMap != null )
then
  $resources.put("new value", "example");
  modify($var) {
    setAttr1("hidden"),
    setResourceMap($resources)
  }
end

(当然,您需要确保您的 resourceMap 已经实例化,因为 null-check。)