Java:如何在不实现接口的情况下评估 EL 表达式 - 独立(在任何 Web 框架之外)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17026863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:45:28  来源:igfitidea点击:

Java: How to evaluate an EL expression - standalone (outside any web framework) without implementing interfaces?

javaelevaluation

提问by Ondra ?i?ka

I'd like to use EL in my application. But I can't find any howto. I usually end up needing some interface for which I don't have an implementation.

我想在我的应用程序中使用 EL。但我找不到任何方法。我通常最终需要一些我没有实现的接口。

I have a map of objects, and I want a string expression like Hello, ${person.name}to be evaluated to a string.

我有一个对象映射,我想要像 Hello 这样的字符串表达式${person.name}被评估为一个字符串。

How can I achieve that, using any of Commons EL, javax.el, OGNL, or such? Must be a standalone library.

如何使用 Commons EL、javax.el、OGNL 等实现这一点?必须是一个独立的库。

And I knowJava: using EL outside J2EE, and have seen JSTL/JSP EL (Expression Language) in a non JSP (standalone) context. That is not what I'm looking for.

而且我知道Java:在 J2EE 之外使用 EL,并且在非 JSP(独立)上下文中看到了JSTL/JSP EL(表达式语言)。那不是我要找的。

What I am looking for is an example of what dependency to add, and then how to initialize a parser which will have:

我正在寻找的是要添加什么依赖项的示例,然后是如何初始化将具有的解析器:

private static String evaluateEL( String expr, Map<String, String> properties );

and allow me to do:

并允许我做:

String greet = evaluateEL("Hello ${person.name}", 
     new HashMap(){{
       put("person", new Person("Ondra"));
     }}
);

And I need it to use some rational value, e.g. ""on nullinstead of throwing NPE or so.

我需要它来使用一些合理的价值,例如""onnull而不是抛出 NPE 左右。

回答by Ondra ?i?ka

There's quite a bunch of EL engines, of which most implement Java Expression Language API.

有相当多的 EL 引擎,其中大多数实现了 Java 表达式语言 API。

Source

来源

For now I ended up with this code using BeanUtils- ugly but works.

现在我最终使用BeanUtils得到了这段代码- 丑陋但有效。

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;

public static class SimpleEvaluator implements IExprLangEvaluator {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger( SimpleEvaluator.class );

    @Override
    public String evaluateEL( String template, Map<String, String> properties ) {

        StringTokenizer st = new StringTokenizer( template );
        String text = st.nextToken("${");
        StringBuilder sb = new StringBuilder();

        // Parse the template: "Hello ${person.name} ${person.surname}, ${person.age}!"
        do{
            try {
                sb.append(text);
                if( ! st.hasMoreTokens() )
                    break;

                // "${foo.bar[a]"
                String expr  = st.nextToken("}");
                // "foo.bar[a].baz"
                expr = expr.substring(2);
                // "foo"
                String var = StringUtils.substringBefore( expr, ".");

                Object subject = properties.get( var );

                // "bar[a].baz"
                String propPath = StringUtils.substringAfter( expr, ".");

                sb.append( resolveProperty( subject, propPath ) );

                text = st.nextToken("${");
                text = text.substring(1);
            } catch( NoSuchElementException ex ){
                // Unclosed ${
                log.warn("Unclosed ${ expression, missing } : " + template);
            }
        } while( true );

        return sb.toString();
    }

    // BeanUtils
    private String resolveProperty( Object subject, String propPath ) {
        if( subject == null ) return "";

        if( propPath == null || propPath.isEmpty() ) return subject.toString();

        try {
            return "" + PropertyUtils.getProperty( subject, propPath );
        } catch(     IllegalAccessException | InvocationTargetException | NoSuchMethodException ex ) {
            log.warn("Failed resolving '" + propPath + "' on " + subject + ":\n    " + ex.getMessage(), ex);
            return "";
        }
    }

}// class SimpleEvaluator

回答by Ondra ?i?ka

I found one at http://juel.sourceforge.net/guide/start.html. Still not exactly 1-liner, but close.

我在http://juel.sourceforge.net/guide/start.html找到了一个。仍然不完全是 1-liner,但很接近。

ExpressionFactory factory = new de.odysseus.el.ExpressionFactoryImpl();
de.odysseus.el.util.SimpleContext context = new de.odysseus.el.util.SimpleContext();
context.setVariable("foo", factory.createValueExpression("bar", String.class));
ValueExpression e = factory.createValueExpression(context, "Hello ${foo}!", String.class);
System.out.println(e.getValue(context)); // --> Hello, bar!

Maven deps:

Maven 部门:

    <!-- Expression language -->
    <dependency>
        <groupId>de.odysseus.juel</groupId>
        <artifactId>juel-api</artifactId>
        <version>2.2.7</version>
    </dependency>
    <dependency>
        <groupId>de.odysseus.juel</groupId>
        <artifactId>juel-impl</artifactId>
        <version>2.2.7</version>
        <type>jar</type>
    </dependency>