Groovy方法从String中动态实例化一个类 [英] Groovy way to dynamically instantiate a class from String
问题描述
这个关于Groovy动态调用静态方法的问题的答案非常有帮助,但我在遇到以下情况时遇到问题:
我定义了一个简单的Groovy类:
class Item {
def id = 1
def data = [a,b]
}
然后,我定义了一个简单的实用程序类,它想动态加载Item类:
class Util {
static def main(args){
def cls =Itemas class
def instance = cls。 newInstance()
println instance.toString()
}
}
Util.groovy与Item.groovy位于同一文件夹中
当我尝试运行Util.groovy时,出现以下错误:
抓住:org.codehaus.groovy.runtime.typehandling.GroovyCastException:
无法投射使用类java.lang.String'
到类'java.lang.Class'的对象'Item'由于:
java.lang.ClassNotFoundException:Item
在Util.main(Util .groovy:3)
我可以使它工作的唯一方法是使用groovyc预编译Item .groovy,但这忽略了Groovy的意义:)解析方案
def instance = this.class。 classLoader.loadClass('Item',true,false)?。newInstance()
The answers of this question about the Groovy way to dynamically invoke a static method were very helpful but I'm having trouble with the following case:
I defined a simple Groovy class:
class Item {
def id = 1
def data = [ "a", "b" ]
}
I then defined a simple utility class that wants to dynamically load the Item class:
class Util {
static def main(args) {
def cls = "Item" as Class
def instance = cls.newInstance()
println instance.toString()
}
}
Util.groovy is in the same folder as Item.groovy
When I try to run Util.groovy I get the following error:
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)
The only way that I could make it work was by using groovyc to precompile Item.groovy, but this misses the point of being Groovy :)
This works, using the underlying GroovyClassLoader
:
def instance = this.class.classLoader.loadClass( 'Item', true, false )?.newInstance()
这篇关于Groovy方法从String中动态实例化一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!