0

我有以下代码:

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

为什么是resultNULL?实例不会有问题story,正如我在其他代码中验证的那样getDescriptions()getDescriptions().get(0)它们都返回非空值。此外,getDescriptions().get(0)确实返回一个非空、非空的字符串值。提前致谢!

4

1 回答 1

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 }
于 2013-10-01T13:33:36.660 回答