为什么Groovy评估器返回NULL?

时间:2013-10-01 13:28:03

标签: groovy nullpointerexception evaluate

我有以下代码:

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值。提前谢谢!

1 个答案:

答案 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 }