droolsdrools-guvnordrools-planner

Drool rule to specify only to fire for Parent not for its child


I have two java object(Let say Parent and Child..child extends parent).But I need to specify rule fire only for parent not for its child.

Ex:

when 
    $raw : Parent()
then
    System.out.println(" Parent")
end
----
when 
    $raw : Child()
then
    System.out.println(" Child")
end

If I try to inject child object as a fact, it fire for both. I am not able to use not Child() bz I have lots of child.Thanks

Best regards, Nipuna.


Solution

  • First, let me say that the necessity of distinguishing a Parent object from any of its subclasses is very likely a design flaw. If you need rules that apply only to the Parent and not to any of its subclasses it is an indication that Parent is going to be processed in parallel to its children. To resolve, don't insert Parent objects but create another subclass

    class ChildWithoutAdditionalProperties extends Parent {
    }
    

    and insert objects of this class.

    Second, not Child() does not match objects of any other class besides Child as your remark "I am not able to use not Child()" seems to indicate: It will match for the absence of any Child fact.

    To test that an object is of a certain class, you can compare the class of that object:

    rule "parent"
    when
        $e: Parent( $e.getClass == Parent.class )
    then
        System.out.println( "found Parent" );
    end