Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何避免MVEL属性访问异常_Java_Mvel - Fatal编程技术网

Java 如何避免MVEL属性访问异常

Java 如何避免MVEL属性访问异常,java,mvel,Java,Mvel,当哈希映射中的顶级键可能存在,也可能不存在时,如何避开PropertyAccessException 在下面的示例中,如果属性存在,它工作正常,但是如果变量映射中不存在该属性,它将抛出PropertyAccessExceptions。我知道我可以使用?用于空安全导航,但当属性存在于顶层时,这不起作用 有什么建议吗 HashMap<String, Object> variables = new HashMap<>(); variables.put("aProperty",

当哈希映射中的顶级键可能存在,也可能不存在时,如何避开PropertyAccessException

在下面的示例中,如果属性存在,它工作正常,但是如果变量映射中不存在该属性,它将抛出PropertyAccessExceptions。我知道我可以使用?用于空安全导航,但当属性存在于顶层时,这不起作用

有什么建议吗

HashMap<String, Object> variables = new HashMap<>();
variables.put("aProperty", "aValue");

Boolean result = MVEL.evalToBoolean("'aValue' == aProperty", variables);
assertThat(result).isTrue();  //This works

result = MVEL.evalToBoolean("'aValue' == aNonExistentProperty", variables);
assertThat(result).isFalse();  //This throws a PropertyAccessException, since aNonExistentProperty is not defined
HashMap variables=newhashmap();
变量。put(“资产”、“价值”);
布尔结果=MVEL.evaltoblean('aValue'==aProperty',变量);
断言(result.isTrue()//这很有效
结果=MVEL.evalToBoolean(“'aValue'==aNonExistentProperty”,变量);
断言(result).isFalse()//这会引发PropertyAccessException,因为未定义aNonExistentProperty

我希望有一个解决方法来避免PropertyAccessException。

我最近也遇到了同样的问题,我发现MVEL有不同的计算表达式的方法,其中之一是,对于布尔值,
公共静态布尔值evalToBoolean(字符串表达式,variableSolverfactory变量)
。当您传递变量映射时,它会在内部实例化
cachingmapvariablesolverfactory
,您可以覆盖它以避免此问题

示例实现如下所示

public class CustomVariableResolvableFactory extends CachingMapVariableResolverFactory{
        public CustomVariableResolvableFactory(Map variables) {
            super(variables);
        }
        @Override
        public boolean isResolveable(String name) {
            if(!super.isResolveable(name))
                variables.put(name, null);
            return true;
        }
    }
该类将确保每当PropertyAccessor检查变量是否存在于求值上下文中时,如果变量不存在,它将设置null并返回true,从而避免PropertyAccessException。
variablesolverfactory
的这个自定义实现可以如下使用

MVEL.eval(表达式,新的CustomVariableResolvableFactory(vars))

我不知道这是一个黑客程序还是打算这样使用,但它能工作