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

我有两节课. 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:没有方法签名:script13561062248721121730020.someMethod()适用于参数类型:(java.lang.String)值:[Yo!]

有任何想法吗?

最佳答案 看起来它是由于调用groovy类加载器方法而发生的:
string one是以文本格式解析脚本.使用文件一个在这里工作:

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

  }
}
点赞