我正在尝试扩展一个 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/