Tolga Evcimen
Tolga Evcimen

Reputation: 7352

How to instantiate an object in a .drl file

I am totally new with this drools staff. Thus I am having a little bit of trouble here.

rule "Raise the alarm when we have one or more fires"
    when
exists Fire()
then 
    insert( new Alarm() );  
end

when I have this code it works fine. But I want to change this a bit like :

rule "Raise the alarm when we have one or more fires"
    when
exists Fire()
then 
    $alarm = new Alarm();
    $alarm.RingBell();
    insert( $alarm );  
end

probably you understood what I am trying to do here. I want to instantiate the Alarm class and fire the RingBell method of it. But it gives me this error

Rule Compilation error : [Rule name='Raise the alarm when we have one or more fires']
    com/sample/Rule_Raise_the_alarm_when_we_have_one_or_more_fires_cd7449c70a6a48c78f4e291495d23b05.java (8:436) : alarm cannot be resolved

java.lang.IllegalArgumentException: Could not parse knowledge.
    at com.sample.DroolsTest.readKnowledgeBase(DroolsTest.java:117)
    at com.sample.DroolsTest.main(DroolsTest.java:28)

If you guys help me out here I would appreciate it :))

Upvotes: 1

Views: 9242

Answers (1)

Esteban Aliverti
Esteban Aliverti

Reputation: 6322

The error is because $alarm variable is never declared. Try to do the following:

rule "Raise the alarm when we have one or more fires"
    when
exists Fire()
then 
    Alarm $alarm = new Alarm();
    $alarm.RingBell();
    insert( $alarm );  
end

The important line is: Alarm $alarm = new Alarm();

Upvotes: 5

Related Questions