我有两个类。一、常规:
class One {
One() {}
def someMethod(String hey) {
println(hey)
}
}
还有两个.groovy:
class Two {
def one
Two() {
Class groovy = ((GroovyClassLoader) this.class.classLoader).parseClass("One.groovy")
one = groovy.newInstance()
one.someMethod("Yo!")
}
}
我用这样的东西实例化两个:
GroovyClassLoader gcl = new GroovyClassLoader();
Class cl = gcl.parseClass(new File("Two.groovy"));
Object instance = cl.newInstance();
但现在我得到
groovy.lang.MissingMethodException: No signature of method: script13561062248721121730020.someMethod() is applicable for argument types: (java.lang.String) values: [Yo!]
有任何想法吗?
最佳答案
似乎是由于调用了 groovy 类加载器方法而发生的:string one是解析文本格式的脚本。使用 File
一个在这里工作:
class Two {
def one
Two() {
Class groovy = ((GroovyClassLoader) this.class.classLoader).parseClass("One.groovy")
assert groovy.superclass == Script // whoops, not what we wanted
Class groovy2 = ((GroovyClassLoader) this.class.classLoader).parseClass(new File("One.groovy"))
one = groovy2.newInstance()
assert one.class == One // now we are talking :-)
one.someMethod("Yo!") // prints fine
}
}
关于class - 为什么我不能从另一个 Groovy 类实例化一个 Groovy 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13993611/