从 String 动态实例化类的 Groovy 方法 [英] Groovy way to dynamically instantiate a class from String

查看:27
本文介绍了从 String 动态实例化类的 Groovy 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

我定义了一个简单的 Groovy 类:

I defined a simple Groovy class:

class Item {
  def id = 1
  def data = [ "a", "b" ]
}

然后我定义了一个简单的实用程序类来动态加载 Item 类:

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 与 Item.groovy 位于同一文件夹中

Util.groovy is in the same folder as Item.groovy

当我尝试运行 Util.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)

我可以让它工作的唯一方法是使用 groovyc 来预编译 Item.groovy,但这错过了成为 Groovy 的重点:)

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 :)

推荐答案

这有效,使用 底层GroovyClassLoader:

This works, using the underlying GroovyClassLoader:

def instance = this.class.classLoader.loadClass( 'Item', true, false )?.newInstance()

这篇关于从 String 动态实例化类的 Groovy 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆