Jexl3 中自定义类的运算符重载/定义 [英] Operator overloading/definition for custom classes in Jexl3
问题描述
我正在尝试在 Jexl 表达式中实现一个行为类似于 Boolean
的自定义类:
I am trying to implement a custom class that should behave like Boolean
in Jexl expressions:
示例:Object result = jexl.createExpression("a || b").evaluate(context)
其中 a
和 b
是自定义类的实例,其中包含 boolean
和应通过评估表达式携带的额外信息,以便它最终可以在 result
中访问.
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
.
我读过 Jexl3 应该支持运算符重载,它似乎具有为自定义类定义自己的运算符所需的所有结构 - 但是我无法理解这样做需要哪些步骤.
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.
我已经尝试通过自定义实现扩展 Uberspect
和 JexlArithmetic
,但是我只发现使用 toBoolean
我可以转换我的自定义对象到 Boolean
(这使得 result
成为 Boolean
- 因此我丢失了所有额外信息).
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).
如何正确使用/扩展 Jexl 为自定义类提供布尔运算符?
推荐答案
只需扩展 JexlArithmetic 类并覆盖其中的 or 方法.
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
}
}
然后尝试以下:
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);
这篇关于Jexl3 中自定义类的运算符重载/定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!