我是流口水的新手,所以请耐心等待。 我有以下规则:
rule "01: Car can not be black"
when
Car(color == "black")
then
System.out.println("Car can not be black");
end
这样做是否有效(其中 Door 是一个以颜色作为成员变量的对象成员):
rule "02: Car's door can not be black"
when
Car(door.color == "black")
then
System.out.println("Car's door can not be black");
end
如果不可能,使用什么模板来匹配解决方案?
最佳答案
只要您的类具有适当命名的 getter,这两条规则都是有效的。
第一条规则适用于类 Car
哪个有公共(public) color
属性(property)或其具有公共(public) getColor
方法:
public class Car {
public String color;
}
// or:
public class Car {
private String color;
public String getColor() {
return this.color;
}
}
同样,如果您的 Car
则第二条规则将起作用。类有公共(public) Door
属性(property)或公众getDoor
方法,并且门同样具有 public Color
或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
如果您需要检查同一扇门的其他属性,这种方法很有用。例如,假设您的汽车有多个门,并且 Car 模型具有类似 List<Door> 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
因为我实际上不需要对黑色圆形的门做任何事情,我只是想确保它存在。
关于java - 在when子句中使用成员对象的字段创建Drools,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60422246/