Jexl3 中自定义类的运算符重载/定义 [英] Operator overloading/definition for custom classes in Jexl3

查看:178
本文介绍了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)

其中 ab 是自定义类的实例,其中包含 boolean 和应通过评估表达式携带的额外信息,以便它最终可以在 result 中访问.

Where aand 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.

我已经尝试通过自定义实现扩展 UberspectJexlArithmetic,但是我只发现使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆