Drools:如何在规则的lhs中使用枚举?

时间:2011-11-21 12:07:19

标签: java drools

我在写一个与lhs中的枚举值匹配的规则时遇到了困难。

例如,如果我有以下枚举:

public enum EStatus {
  OK,
  NOT_OK
}

我想用这样的东西:

rule "my rule"
dialect "java"
    when        
        status : EStatus()                      // --> this works, but I want to be more specific
        // status : EStatus(this == EStatus.OK) // --> doesn't work. How can I make it work?
    then
        // ...
end

这在Drools中甚至可能吗?我使用的是5.1.1版本。

4 个答案:

答案 0 :(得分:7)

这对我有用:

rule "my rule"
when
    Ticket(status == EStatus.OK)
then
    ...
end

因此也应该有效:

rule "my rule"
when
    EStatus(this == EStatus.OK)
then
    ...
end

验证它是否仍然出现在Drools 5.3中并在jira

中提交错误

答案 1 :(得分:0)

我试图在LHS [Ticket(status == EStatus.OK)]上使用Enum,我得到的编译时错误如下:

BuildError:无法分析表达式状态== EStatus.OK 错误:无法使用strict-mode解决方法:....

<强>解决方案:

在规则LHS中,我们必须与常数值进行比较...例如:user:User(age&gt; 60) - 这里我们将年龄与常数值60进行比较。

因此,对于使用Enum,Ticket(status == EStatus.OK)...我必须使用一些常量代替EStatus.OK来将其与状态进行比较。出于这个原因,我在Enum中使用了一种静态方法。

所以,规则的LHS现在看起来像:票证(状态== EStatus.getEStatus(1))

和EStatus枚举如下:

public enum EStatus {

// you can use values other than int also
OK(1),
ERROR(2);

private int value;

EStatus(int number)     {         this.value =数字;     }

public int valueOf()
{
    return this.value;
}

public static EStatus getEStatus(int value){
    EStatus eStatus = null;

    for(EStatus e : EStatus.values()){
        if(e.valueOf() == value){
            eStatus = d;
            break;
        }
    }

    return eStatus;
}

}

我在Linux和Windows环境中使用jdk 1.6进行了测试。

享受编码!

答案 2 :(得分:0)

另一种解决方案。您只需要在Estatus枚举中添加getter,如下所示。

public enum EStatus  {
OK,
NOT_OK;

public EStatus getValue(){
    return this;
}

}

然后您可以编写如下规则

rule "my rule"
when
    EStatus(value == EStatus.OK)
then
    ...
end

答案 3 :(得分:0)

这也应该达到目的:

rule "my rule"
when
    $status : EStatus()
    eval ( $status == EStatus.OK )
then
    ...
end