使用`evaluate`函数.为什么不起作用? [英] Using `evaluate` function. Why it doesn't work?

查看:161
本文介绍了使用`evaluate`函数.为什么不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

evaluate ("def test() { println \"Test is successful!\" }")
test()

导致异常:

FATAL:方法的无签名:script1409644336796288288198097.test()适用于参数类型:()值:[] 可能的解决方案:use([Ljava.lang.Object;),getAt(java.lang.String),use(java.util.List,groovy.lang.Closure),use(java.lang.Class,groovy.lang.闭包),wait(),wait(long) groovy.lang.MissingMethodException:方法的无签名:script1409644336796288288198097.test()适用于参数类型:()值:[] 可能的解决方案:use([Ljava.lang.Object;),getAt(java.lang.String),use(java.util.List,groovy.lang.Closure),use(java.lang.Class,groovy.lang.闭包),wait(),wait(long) 在org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55) ...

FATAL: No signature of method: script1409644336796288198097.test() is applicable for argument types: () values: [] Possible solutions: use([Ljava.lang.Object;), getAt(java.lang.String), use(java.util.List, groovy.lang.Closure), use(java.lang.Class, groovy.lang.Closure), wait(), wait(long) groovy.lang.MissingMethodException: No signature of method: script1409644336796288198097.test() is applicable for argument types: () values: [] Possible solutions: use([Ljava.lang.Object;), getAt(java.lang.String), use(java.util.List, groovy.lang.Closure), use(java.lang.Class, groovy.lang.Closure), wait(), wait(long) at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55) ...

我做错了什么?

推荐答案

该脚本评估结果为null.您应该返回某些内容或执行脚本并返回结果.

That script evaluation results in null. You should either return something or execute the script and return the result.

返回闭包而不定义方法的示例:

An example returning a closure instead of defining a method:

test = evaluate ('return { "Test is successful!" }')
assert test() == "Test is successful!"

还有一个脚本本身执行方法的示例:

And an example where the script executes the method itself:

result = evaluate 'def test() { "eval test" }; return test()'
assert result == "eval test"

如果您无法更改脚本代码,则可以从脚本中解析一个类,创建一个新对象,然后执行test()方法:

If you cannot change the script code, you may parse a class from the script, create a new object, and then execute the test() method:

def parent = getClass().getClassLoader()
def loader = new GroovyClassLoader(parent)
def clazz = loader.parseClass('def test() { "new class definition" }');

obj = clazz.newInstance()
assert obj.test() == "new class definition"

这篇关于使用`evaluate`函数.为什么不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆