Sunil Bhagat
Sunil Bhagat

Reputation: 99

Instancof not working in drools rule engine drl file

i am passing a list List<ArrayList> list = new ArrayList<>(); to drools and the inner arraylist contains Objects of Class TaxPayer , and my rule is like

rule "test1"
when
    $l:TaxList($k : list)
    $b:ArrayList() from $k
    $a:Object() from $b
then
    if($a instanceof TaxPayer){
        $b.add(new TaxPayer(7,6,5,4,3,2,1));
    }
    if($a instanceof Object){
        $b.add(new TaxPayer(1,2,3,4,5,6,7));
    }

end

the second if is working fine, but it is not going in the first if even though it is an instance of TaxPayer

Upvotes: 0

Views: 377

Answers (1)

Prog_G
Prog_G

Reputation: 1615

I tried executing the above rule as :

rule "test"
when
    $c : TaxList($list : list)
    $b : ArrayList()  from $list
    $testobj: Object() from $b
then
    if ($testobj instanceof TaxPayer){
        System.out.println("inside if 1");
    }
    if ($testobj instanceof Object) {
        System.out.println("inside if 2 ");
    }
end

It is working fine for me. The output I am getting is :

inside if 1
inside if 2 
inside if 1
inside if 2 ...

Can you elaborate on your problem and add the respective java code to the question so that I will be able to understand how are you inserting the object into the drools session. Please add the Java code snippet and TaxList class.

EDIT:

Main.java:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        KieServices kieServices = KieServices.Factory.get();
        KieContainer kieContainer = kieServices.newKieClasspathContainer();
        KieSession kieSession = kieContainer.newKieSession("test");
        ArrayList<TaxPayer> taxPayers = new ArrayList<>();
        taxPayers.add(new TaxPayer(1));
        taxPayers.add(new TaxPayer(2));
        ArrayList<ArrayList> arrayLists = new ArrayList<>();
        arrayLists.add(taxPayers);
        TaxList taxList = new TaxList(arrayLists);
        kieSession.insert(taxList);
        kieSession.fireAllRules();
    }
}

TaxList.java:

import java.util.ArrayList;

public class TaxList {
    ArrayList<ArrayList> list = new ArrayList<>();


    public TaxList(ArrayList<ArrayList> list) {
        this.list = list;
    }

    public ArrayList<ArrayList> getList() {
        return list;
    }

    public void setList(ArrayList<ArrayList> list) {
        this.list = list;
    }
}

TaxPayer.java:

public class TaxPayer {
    private int id;

    public TaxPayer(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

Upvotes: 0

Related Questions