为什么我不能从另一个Groovy类实例化Groovy类?

时间:2012-12-21 16:21:17

标签: class groovy classloader instance

我有两节课。 One.groovy:

class One {

  One() {}

  def someMethod(String hey) {
    println(hey)
  }
}

和Two.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!]

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

似乎是因为调用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

  }
}