java - 在when子句中使用成员对象的字段创建Drools

标签 java drools

我是流口水的新手,所以请耐心等待。 我有以下规则:

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 ColorgetColor() .

编写检查门不是黑色的第二条规则的另一种方法如下:

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/

相关文章:

java - 基于时间运算符的累加/收集

Drools JBOSS 规则嵌套 IF

java - 在Spring编译期间用另一个注释替换一个注释?

java - 如何防止 jarsign 脚本覆盖已签名 jar 中的现有 list 值?

java - 使用负边权重的 Bellman-Ford 追踪最长路径

java - 卡夫卡流 : Processor sometimes processes same messages upon application restart

java - StatelessKnowledgeSession 和 Drools Flow

Java:使用 JOptionPane.showInputDialog(null, "Text") 的多行文本;

java - 分析 native 方法上的卡住线程

java - 比较套装流口水