Search code examples
javaintegerdroolsclasscastexception

Comparing integers in drools causes cast exception


I have a simple Drools rule where I am converting a string to an integer and then comparing it with another integer. Like so:

when
    $list : List(size > 0 )
    $m1 : Map() from $list.get(0)
    $var1 : Map(stringToInt(this["number"]) <= 0) from $list.get(0)

This should check if the string value of "number" in my map is less than or equal to 0 after being converted. stringToInt is just a helper function I wrote that calls Integer.parseInt and catches exceptions.

I get this error though when I try to run the rule:

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
    at org.mvel2.ast.Negation.getReducedValueAccelerated(Negation.java:48)

The dialect is set to java and my version of drools is 6.4.0. How do I get around this error?

EDIT: string to int:

public static int stringToInt(String s) {
    try {
        int num = Integer.parseInt(s);
        return num;
    } catch (Exception e) {
        return -1;
    }
}

Solution

  • This works for me.

    Creating a session, all options at default. Inserting:

    Map<String,String> map = new HashMap<>();
    map.put( "number", "4711" );
    List<Map<String,String>> list = new ArrayList<>();
    list.add( map );
    kieSession.insert( list );
    

    Running a drl:

    import static map.Main.stringToInt;
    import java.util.*;
    rule "int from map"
    when
      $list : List(size > 0 ) 
      $m1 : Map() from $list.get(0)
      $var1 : Map(stringToInt(this["number"]) > 0 ) from $list.get(0)
    then
      System.out.println( "got 4711" );
    end
    

    I even kept the redundant first (empty) Map pattern.

    Check that your classpath includes mvel2-2.2.8.Final.jar and no other version. (This is where class Negation is.)

    Check that you have reported the rule as it is in your code, not omitting the real trigger of the exception.