I am new to drools, so please bear with me. I have the following rule:
rule "01: Car can not be black"
when
Car(color == "black")
then
System.out.println("Car can not be black");
end
Would it work doing this (where Door is an object member having color as a member variable):
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
If not possible, what template to use to match the solution?
Both of these rules are valid, as long as your class has the appropriately named getters.
The first rule will work for a class Car
which either has a public color
property or it has a public getColor
method:
public class Car {
public String color;
}
// or:
public class Car {
private String color;
public String getColor() {
return this.color;
}
}
Similarly, the second rule will work if your Car
class has a public Door
property or a public getDoor
method, and the Door has, similarly, either public Color
or getColor()
.
Another way to write the second rule that checks that the door is not black would be like this:
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
This way is useful if you need to check other properties of the same door. For example, let's say that your car has multiple doors, and the Car model has a method like List<Door> getDoors();
. To check if there is any black and round door, you could do:
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
Here I used exists
because I don't actually need to do anything with the door that is black and round, I just want to make sure it exists.