groovy - 如何设置嵌入式 Groovy 脚本类路径?

标签 groovy eclipse-plugin classpath embedded-language

我正在尝试扩展一个 Eclipse 代码生成器(用于从 Hibernate VO 生成 DTO)- 它使用 Groovy 作为其模板系统。

它用来创建 groovy 脚本的代码有点奇怪(不是我在 Groovy 文档中看到的)但它有效,主要是:

GroovyShell shell = new GroovyShell();
script = shell.parse(source);

然后,稍后:

Binding binding = (bindings == null ? new Binding() : new Binding(bindings));
Script scriptInstance = InvokerHelper.createScript(script.getClass(), binding);
scriptInstance.setProperty("out", out);
scriptInstance.run();
out.flush();

现在,这工作得很好,直到它遇到对不直接在项目中的对象的引用。在脚本中,它遍历它正在处理的类的属性——当它这样做时,Groovy 会查看所有方法,当它找不到其中一个方法参数的类定义时,它就会崩溃。在这种情况下,当它找到任何对 Hibernate 的引用时,它就会死掉,但我相信它会随着更多的引用而崩溃。它不需要对它们做任何事情,但它无法在不知道它们显然是什么的情况下生存。

Script似乎没有我可以提供任何类路径信息的类加载器,所以我尝试将它提供给 GroovyShell - 没有区别。

解决此问题的正确方法是什么,以便 Groovy 解释器可以找到我引用 Jars 的项目?

最佳答案

我遇到了这个确切的问题,并通过创建我自己的 URLClassLoader 并使用反射调用 protected 方法来向 ClassPath 添加新路径来解决它

// Specify the path you want to add
URL url = new URL("file://path/to/classes/here");

// Create a new class loader as a child of the default system class loader
ClassLoader loader = new URLClassLoader(System.getClass().getClassLoader()); 

// Get the AddURL method and call it
Method method = URLClassLoader.class.getDeclaredMethod("addURL",new Class[]{URL.class});
method.setAccessible(true);
method.invoke(loader,new Object[]{ url });

GroovyShell shell = new GroovyShell( loader );

关于groovy - 如何设置嵌入式 Groovy 脚本类路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/726736/

相关文章:

grails - 在运行时动态设置Grails DataSource到内存中的H2实例

Jenkins 管道 : Shouldn't closures resolve variables the same inside parallel as outside?

java - Fitnesse 无法在 Java 中引用外部 API?

java - 无法在 Docker 环境中使用 Spring ResourceUtils 或 DefaultResourceLoader 获取类路径资源

java - NoClassDefFoundError 到底什么时候抛出?

Jenkins 在 groovy 脚本中检索主动选择参数

groovy - 为 "function_score"运行 groovy 脚本时出现问题?

java - 我在哪里可以找到 RCP 产品中的系统输出打印件?

java - WindowBuilder Pro VS Matisse 4 MyEclipse

android - 带有 ADT : Moving installed component from one pc to another 的 Google Android 和 Eclipse