我第一次使用mvel。简单地运行TemplateRuntime.eval时,使用@includeNamed可以正常工作。
但是如果我尝试使用CompiledTemplate,它就会抛出一个NPE。难道我做错了什么?或者这是一个错误?我正在使用mvel 2.1.4.Final
public class App {
public static void main(String[] args) {
TemplateRegistry registry = new SimpleTemplateRegistry();
registry.addNamedTemplate("world", TemplateCompiler.compileTemplate("world!!!"));
System.out.println(TemplateRuntime.eval("Eval Hello: @includeNamed{'world'}", null, registry));
CompiledTemplate ct = TemplateCompiler.compileTemplate("Compile Hello: @includeNamed{'world'}");
System.out.println(TemplateRuntime.execute(ct, null, registry));
}
}
堆栈跟踪(注意:Eval打印正常):
Eval Hello: world!!!
Exception in thread "main" java.lang.NullPointerException
at org.mvel2.integration.impl.StackResetResolverFactory.<init>(StackResetResolverFactory.java:15)
at org.mvel2.compiler.CompiledExpression.getDirectValue(CompiledExpression.java:123)
at org.mvel2.compiler.CompiledExpression.getValue(CompiledExpression.java:119)
at org.mvel2.compiler.CompiledExpression.getValue(CompiledExpression.java:113)
at org.mvel2.MVEL.executeExpression(MVEL.java:930)
at org.mvel2.templates.res.CompiledNamedIncludeNode.eval(CompiledNamedIncludeNode.java:56)
at org.mvel2.templates.res.TextNode.eval(TextNode.java:42)
at org.mvel2.templates.res.TextNode.eval(TextNode.java:42)
at org.mvel2.templates.TemplateRuntime.execute(TemplateRuntime.java:285)
at org.mvel2.templates.TemplateRuntime.execute(TemplateRuntime.java:247)
at org.mvel2.templates.TemplateRuntime.execute(TemplateRuntime.java:255)
at org.mvel2.templates.TemplateRuntime.execute(TemplateRuntime.java:187)
at mveltest.App.main(App.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
答案 0 :(得分:0)
好吧,这似乎是一个错误。我注意到当调用variableResolverFactory.someMethod时,NPE发生在StackResetResolverFactory的构造函数中。
因此,作为一种解决方法,我使用带有VariableResolverFactory的execute方法。
Map<String, Object> dummyVariableMap = new HashMap<String, Object>();
VariableResolverFactory dummyResolverFactory = new SimpleVariableResolverFactory(dummyVariableMap);
System.out.println(TemplateRuntime.execute(ct, null, dummyResolverFactory, registry));
奇怪的是,我认为使用命名模板执行CompiledTemplate将是一个非常常见的用例。