情况很简单。我创建了一个规则文件:
package org.domain.rules;
dialect "mvel"
import eu.ohim.fsp.core.configuration.domain.xsd.Section;
global java.lang.String sectionName;
rule "rule 1"
salience 1000
when
Section($name : nameOfTheSection)
eval(sectionName == null)
then
System.out.println("Section: " + $name+ "("+$name.length()+")");
System.out.println("Section Name: " + sectionName + "("+sectionName.length()+")");
System.out.println("Mark Details: " + sectionName.equals(null));
end
在触发规则之前,我添加了具有有效 coreName
和全局变量的 Section 对象:
public void fireInserted(Section section1) {
kstateful.insert(section1);
kstateful.setGlobal("sectionName", new String("markudetails"));
kstateful.fireAllRules();
}
结果是:
Section: markudetails(12)
Section Name: markudetails(12)
Mark Details: false
问题:这怎么可能? when 部分为空,then 部分不为空!!!
最佳答案
全局变量不是知识库的一部分,而是一个单独的 channel ,用于将某些上下文推送到规则执行中。在 when
子句中使用它们是不合适的。在您的案例中它为 null
的确切原因可能很难追踪,因为规则激活与规则执行完全分离。变量可能不会在 when
子句评估时绑定(bind),但会在 then
子句执行时绑定(bind)。
总而言之:不要在 when
子句中使用全局变量,这不是它们的用途。
您的问题有一个简单的通用解决方案:您可以将配置对象插入知识中。该对象可以具有您想要的“sectionName”属性,然后您会发现它很容易在 when
中进行测试。
顺便说一句,测试 object.equals(null)
是没有意义的——这永远不会产生 true
。也不需要使用 new String("markudetails")
。而是只使用 "markudetails"
。
关于java - Drools:字符串全局变量的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11223537/