Search code examples
javadroolsrule-enginecomplex-event-processingdrools-fusion

Drools rule language: strange behaviour with class fields


I recently noticed some strange behaviour with drools rules. I had class HeartRate and it has the following fields:

int heartRate;
Date timeStamp;
String macAddress;

My rule file is the following:

import drools.HeartRate
import drools.Action

declare HeartRate
    @role(event)
end

rule "HEARTRATE RULE 1"
when
    $heartRate : HeartRate(heartRate >= 180) from entry-point "entryHeartRate"
then
    Action.handleAction(1,"Heart rate is to high!");
end

I want to change the field heartRate to heartrate and I change the field name in my rule also so that my new rule is now:

rule "HEARTRATE RULE 1"
when
    $heartRate : HeartRate(heartrate >= 180) from entry-point "entryHeartRate"
then
    Action.handleAction(1,"Heart rate is to high!");
end

But this gives errors namely that drools can't resolve the field heartrate. But when I change the rule back to the original so with heartRate it works event though such a field doesn't exist anymore. I get the following error:

[Unable to Analyse Expression heartrate >= 180:
[Error: unable to resolve method using strict-mode: drools.HeartRate.heartrate()]
Exception in thread "main" java.lang.RuntimeException: Unable to compile drl".
[Near : {... heartrate >= 180 ....}]
             ^
[Line: 26, Column: 4] : [Rule name='HEARTRATE RULE 1']
]
    at drools.Main.initDrools(Main.java:53)
    at drools.Main.main(Main.java:39)
C:\Users\Tim Deweert\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

Solution

  • Your classes are supposed to follow the Java Beans specification, and Drools will try to locate getSomeField if you use someField in a constraint. It doesn't matter how the private instance field itself is called.

    If the field is public, it will be used if the name matches. Otherwise a getter is used if its name matches according to the rule given above.