Java 使用成员对象创建Drools';when子句中的s字段
我不太会流口水,所以请容忍我。 我有以下规则:Java 使用成员对象创建Drools';when子句中的s字段,java,drools,Java,Drools,我不太会流口水,所以请容忍我。 我有以下规则: rule "01: Car can not be black" when Car(color == "black") then System.out.println("Car can not be black"); end 这样做是否可行(门是一个对象成员,其颜色作为成员变量): 如果不可能,使用什么模板来匹配解决方案?只要类具有适当命名的getter,这两个规则都是有效的 第一条规则适用于具有公共color属性或具有
rule "01: Car can not be black"
when
Car(color == "black")
then
System.out.println("Car can not be black");
end
这样做是否可行(门是一个对象成员,其颜色作为成员变量):
如果不可能,使用什么模板来匹配解决方案?只要类具有适当命名的getter,这两个规则都是有效的 第一条规则适用于具有公共
color
属性或具有公共getColor
方法的类Car
:
public class Car {
public String color;
}
// or:
public class Car {
private String color;
public String getColor() {
return this.color;
}
}
类似地,如果您的Car
类具有publicDoor
属性或publicgetDoor
方法,并且该门具有publicColor
或getColor()
编写检查门是否为黑色的第二条规则的另一种方法如下:
rule "03: Another way to make sure the car's door cannot be black"
when
Car( $door: door != null ) // gets the Door from the car
Door( color == "black" ) from $door // checks if the Door is black
then
System.out.println("Car's door cannot be black");
end
如果需要检查同一门的其他属性,此方法非常有用。例如,假设您的汽车有多扇门,汽车模型有一个类似于List getDoors()的方法代码>。要检查是否有黑色和圆形的门,您可以执行以下操作:
rule "04: A car cannot have any black and round doors"
when
Car( $doors: doors != null ) // get all of the Doors for the car
// finds that any one door is both black and round:
exists(Door( color == "black",
shape == "round" ) from $doors)
then
//...
end
在这里,我使用了exists
,因为我实际上不需要对黑色和圆形的门做任何事情,我只想确保它存在 是的,以上两条规则都是有效的。我们可以在when子句中加上“and”和“or”吗?when Car(door.color==“black”)和Car(door.shape==“round”)然后在你的例子中,如果你想检查一扇车门是黑色的,而一扇车门是圆形的(不一定是同一扇门),你可以做Car(door.color==“black”,door.shape==“round”)
。如果您想检查同一扇门是否是黑色和圆形的,那么您应该像我发布的第三个规则示例一样,从$door检查门(颜色==“黑色”,形状==“圆形”)
。when子句中的逗号表示“and”--这是所有条件必须匹配的。或者您可以选择&&
和|
条件。我建议不要使用和
和或
关键字,因为它们的行为并不总是如您所期望的那样。
rule "04: A car cannot have any black and round doors"
when
Car( $doors: doors != null ) // get all of the Doors for the car
// finds that any one door is both black and round:
exists(Door( color == "black",
shape == "round" ) from $doors)
then
//...
end