【发布时间】:2011-10-13 18:02:04
【问题描述】:
this question about the Groovy way to dynamically invoke a static method 的回答非常有帮助,但我遇到了以下情况:
我定义了一个简单的 Groovy 类:
class Item {
def id = 1
def data = [ "a", "b" ]
}
然后我定义了一个简单的实用程序类,它想要动态加载 Item 类:
class Util {
static def main(args) {
def cls = "Item" as Class
def instance = cls.newInstance()
println instance.toString()
}
}
Util.groovy 与 Item.groovy 位于同一文件夹中
当我尝试运行 Util.groovy 时,出现以下错误:
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object 'Item' with class 'java.lang.String'
to class 'java.lang.Class' due to:
java.lang.ClassNotFoundException: Item
at Util.main(Util.groovy:3)
我可以让它工作的唯一方法是使用 groovyc 预编译 Item.groovy,但这错过了成为 Groovy 的意义 :)
【问题讨论】:
标签: groovy