为什么我不能从另一个Groovy类实例化Groovy类? [英] Why can't I instantiate a Groovy class from another Groovy class?
问题描述
class One {
One(){}
def someMethod(String hey){
println(hey)
}
}
和Two.groovy
class Two {
def one
Two(){
类groovy =((GroovyClassLoader)this.class.classLoader).parseClass(One.groovy)
one = groovy.newInstance()
one.someMethod(Yo!)
}
}
I实例化两个像这样的东西:
GroovyClassLoader gcl = new GroovyClassLoader();
Class cl = gcl.parseClass(new File(Two.groovy));
Object instance = cl.newInstance();
但现在我得到 groovy.lang.MissingMethodException:没有签名的方法: script13561062248721121730020.someMethod()适用于参数类型:(java.lang.String)values:[Yo!]
任何想法? / p>
看起来像是由于groovy类加载器方法被调用而发生的: string one 是以文本格式解析脚本。使用文件
在这里工作:
class Two {
def one
两个(){
类groovy =((GroovyClassLoader)this.class.classLoader).parseClass(One.groovy)
assert groovy.superclass ==脚本//哎呀,不是我们想要的
类groovy2 =((GroovyClassLoader)this.class.classLoader).parseClass new File(One.groovy)
one = groovy2.newInstance()
assert one.class == One // now we're talking :-)
one.someMethod(Yo!)//打印罚款
}
}
I have two classes. One.groovy:
class One {
One() {}
def someMethod(String hey) {
println(hey)
}
}
And Two.groovy:
class Two {
def one
Two() {
Class groovy = ((GroovyClassLoader) this.class.classLoader).parseClass("One.groovy")
one = groovy.newInstance()
one.someMethod("Yo!")
}
}
I instantiate Two with something like this:
GroovyClassLoader gcl = new GroovyClassLoader();
Class cl = gcl.parseClass(new File("Two.groovy"));
Object instance = cl.newInstance();
But now I get groovy.lang.MissingMethodException: No signature of method: script13561062248721121730020.someMethod() is applicable for argument types: (java.lang.String) values: [Yo!]
Any ideas?
Seems like it is occurring due to the groovy class loader method being called: the string one is to parse a script in text format. Using the File
one worked here:
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
}
}
这篇关于为什么我不能从另一个Groovy类实例化Groovy类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!