这里发生了什么?
import java.lang.reflect.Method
class MyClass{
String method1(Closure c){
println 'method'
c() + ' method 1'
}
String method2(){
println 'method'
'method 2'
}
}
def m = new MyClass()
def c = {'closure'}
println m.method1(c)
Method mr2 = MyClass.getMethod('method2')
println mr2
println mr2.invoke(m)
println '---'
Method mr1 = MyClass.getMethod('method1', c)
println mr1
println mr1.invoke(m)
println '---'
产生这个(在Jenkins groovy控制台中)
closure method 1
public java.lang.String MyClass.method2()
method 2
---
groovy.lang.MissingMethodException: No signature of method: static MyClass.getMethod() is applicable for argument types: (java.lang.String, Script1$_run_closure1) values: [method1, Script1$_run_closure1@1242bced]
Possible solutions: method2()
at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1367)
at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1353)
at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:50)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
at Script1.run(Script1.groovy:27)
.
.
.
最终我希望能够在使用反射选择方法后将groovy闭包传递给java方法,但我似乎无法使用闭包作为参数获取方法
答案 0 :(得分:0)
您需要更改:
Method mr1 = MyClass.getMethod('method1', c)
println mr1
println mr1.invoke(m)
要:
Method mr1 = MyClass.getMethod('method1', Closure)
println mr1
println mr1.invoke(m, c)