我有以下代码:
Binding binding = new Binding();
binding.setVariable("story", storyFactory.newStory());
GroovyShell shell = new GroovyShell(binding);
exp = getExpression();
System.out.println("Expression: " + exp);
Object result = (Object)shell.evaluate(exp);
产生以下NullPointerException和控制台输出:
Expression: story.getDescriptions().get(0).setText(story.getDescriptions().get(0).getText().replace("@", "at").replace("\"", "'").replace("%", "percent"));
java.lang.NullPointerException
at com.me.myapp.GroovyEvaluator._evaluate(GroovyEvaluator.java:56)
at com.me.myapp.testing.expressions.Driver.runEvaluator(Driver.java:131)
at com.me.myapp.testing.expressions.Driver.run(Driver.java:65)
at com.me.myapp.testing.expressions.Driver.main(Driver.java:31)
null
为什么result
为空?它不是story
实例的问题,因为我已在其他代码中验证getDescriptions()
和getDescriptions().get(0)
都返回非空值。此外,getDescriptions().get(0)
确实返回非空的非空String值。提前谢谢!
答案 0 :(得分:0)
它返回值:
story.getDescriptions().get(0).setText
我认为setText
有一个void
返回类型
因此,您获得了null
尝试将表达式更改为:
story.descriptions.get( 0 ).with { d ->
d.text = d.text.replace("@", "at")
.replace( '"', "'")
.replace( "%", "percent" )
d
}
(或者像一行一样):
story.descriptions.get( 0 ).with { d -> d.text = d.text.replace("@", "at").replace( '"', "'").replace( "%", "percent" ) ; d }