Reputation: 1202
I am trying to implement a custom class that should behave like Boolean
in Jexl expressions:
Example:
Object result = jexl.createExpression("a || b").evaluate(context)
Where a
and b
are instances of a custom class that contains an boolean
and extra information that should be carried through the evaluated expresssion so that it can be accessed in the end in result
.
I have read that Jexl3 should support operator overloading and it seems to have all the necessary structures for defining own operators for custom classes - however I am unable to understand what steps are necessary for doing so.
I already tries to extend Uberspect
and JexlArithmetic
by custom implementations, however I only found out that using toBoolean
I can convert my custom objects to Boolean
(which makes result
a Boolean
- hence I loose all the extra information).
How to use/extend Jexl properly to provide boolean operators for custom classes?
Upvotes: 2
Views: 1243
Reputation: 988
Just extend JexlArithmetic class and override or method inside.
public class ExtendedJexlArithmetic extends JexlArithmetic
{
public Object or(YourCustomClass left, YourCustomClass right)
{
return left.or(right); // make sure you've implemented 'or' method inside your class
}
}
And then try below:
JexlContext jexlContext = new MapContext();
jexlContext.set("a", new YourCustomClass());
jexlContext.set("b", new YourCustomClass());
JexlEngine jexlEngine=new JexlBuilder().arithmetic(new ExtendedJexlArithmetic (true)).create();
System.out.println(jexlEngine.createScript("a | b").execute(jexlContext);
Upvotes: 3
Reputation: 364
You are on the right path, you need to extend JexlArithmetic and implement your overloads. The various overloadable operators are described in http://commons.apache.org/proper/commons-jexl/apidocs/org/apache/commons/jexl3/JexlOperator.html . There is a test/example in http://svn.apache.org/viewvc/commons/proper/jexl/tags/COMMONS_JEXL_3_1/src/test/java/org/apache/commons/jexl3/ArithmeticTest.java?view=markup#l666 .
Upvotes: 1