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 的意义:)
最佳答案
使用 underlying GroovyClassLoader
就可以了:
def instance = this.class.classLoader.loadClass( 'Item', true, false )?.newInstance()
关于从 String 动态实例化类的 Groovy 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7758398/