从 String 动态实例化类的 Groovy 方法

标签 groovy

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/

相关文章:

groovy - 为什么 `++` 在 Groovy 中增加 final 字段?

groovy - 如何在groovy中合并两个 map

testing - spring 尝试在 Mocked 实例中注入(inject) @Autowired 依赖项

unit-testing - 在 spock 中运行测试时出现 MissingPropertyException

grails - 在 Groovy 中覆盖 Joda DateTime toString

grails - 尝试使循环与GPar并行执行失败

elasticsearch - 索引创建成功,但不会重新索引新数据

jenkins - 如何使用 GitHub Org 插件从 jenkins 管道 (jenkinsfile) 触发另一个作业?

groovy - Groovy 中的深复制映射

spring - 如何在ElasticSearch中编写搜索查询?