JEXL:如何自定义属性访问器

时间:2020-03-11 08:49:46

标签: java jexl

我有数据对象,您可以将其视为“简化地图”。有方法exited with 0 1-1-1-1-1 2-2-2-2-2 get(String),但基本上就是这样。

现在,我想使用JEXL评估数据对象上的复杂表达式。我可以通过创建一个自定义JexlContext来做到这一点,它适用于“ foo” put(String,Object)之类的表达式。但是,一旦我尝试使用“ foo.bar” 这样的表达式,Jexl就会失败,并显示一条错误消息“ unsolvable property”。 显然,Jexl使用我的自定义JexlContext来评估“ foo” ,但是不能在foo对象上评估“ bar” 。 我的印象是,我必须使用自定义的PropertyResolver。我可以实现,但我不知道。 JexlUberspect不包含foo != nullsetResolvers之类的方法。

1 个答案:

答案 0 :(得分:0)

类似于重复的问题,我想你可以做到:

public class ExtendedJexlArithmetic extends JexlArithmetic
{
    public Object propertyGet(YourCustomClass left, YourCustomClass right)
    {
       // ...
    }
}

JexlEngine jexlEngine=new JexlBuilder().arithmetic(new ExtendedJexlArithmetic (true)).create();
// or
JexlEngine jexl = new JexlEngine(null, new ExtendedJexlArithmetic(), null, null);

摘自https://commons.apache.org/proper/commons-jexl/apidocs/org/apache/commons/jexl3/package-summary.html

上的文档

您还可以添加方法以重载属性获取器和设置器运算符的行为。 JexlArithmetic实例的名为propertyGet / propertySet / arrayGet / arraySet的公共方法是可能的覆盖,将在适当时调用。下表概述了语法形式与调用方法之间的关系,其中V是属性值类,O是对象类,P是属性标识符类(通常是String或Integer)。

Expression                   Method Template
foo.property              public V propertyGet(O obj, P property);

foo.property = value      public V propertySet(O obj, P property, V value);

foo[property]             public V arrayGet(O obj, P property, V value);

foo[property] = value     public V arraySet(O obj, P property, V value);