我有一个使用多个groovy脚本的Java应用程序,编译后使用 GroovyShell.parse(text)
方法将脚本缓存在内存中 .
是否有可能只编译一次这些脚本并在磁盘/数据库上保留二进制类?以下代码将在 /tmp
中存储二进制类;
CompilerConfiguration compilerConfiguration=new CompilerConfiguration();
compilerConfiguration.setTargetDirectory("/tmp/");
GroovyShell shell=new GroovyShell(compilerConfiguration);
shell.parse("println 'foo';","myScript1");
shell.parse("println 'bar';","myScript2");
运行此代码后,我可以在 /tmp/
目录中看到 myScript1.class
和 myScript2.class
,但尝试使用上面的代码在应用程序重启后加载类(因此不需要重新编译)会失败:
CompilerConfiguration compilerConfiguration=new CompilerConfiguration();
compilerConfiguration.setTargetDirectory("/tmp/");
GroovyShell shell=new GroovyShell(compilerConfiguration);
Class clazz=shell.getClassLoader().loadClass("myScript1");
从 GroovyClassLoader
的源代码中我看不到任何加载 defineClass(java.lang.String, byte[])
方法之外的二进制类的方法,这在尝试加载类时会产生以下异常:
Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value 2901213189 in class file myScript1
有没有其他方法直接加载编译的groovy类?
1 回答
我想通了,只是提供
URLClassLoader
与GroovyShell
的构造函数相同的目录按预期工作 .