【问题标题】:Why can't I instantiate a Groovy class from another Groovy class?为什么我不能从另一个 Groovy 类实例化一个 Groovy 类?
【发布时间】:2012-12-21 16:21:17
【问题描述】:

我有两节课。 One.groovy:

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!]

有什么想法吗?

【问题讨论】:

  • parseClass(String) 期望脚本/类的文本作为其参数,而不是文件名。因此,您正在编译一个包含单个语句的脚本,该语句获取名为 One 的绑定变量,然后尝试获取其 groovy 属性的值。
  • 我假设你知道你可以说“def one=new One()”...?
  • @BillK 当然。我在本地示例中使用了one 作为实例变量,它只是卡在这里。
  • 我的意思是你根本不需要使用 GroovyClassLoader,如果你从两个调用 new One() 并且 .groovy 文件在类路径中,它就可以工作。

标签: class groovy classloader instance


【解决方案1】:

似乎是由于调用了 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

  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2014-03-08
    • 1970-01-01
    • 2013-05-02
    • 2012-02-26
    • 1970-01-01
    相关资源
    最近更新 更多