I have a Java application that uses multiple groovy scripts, the scripts get cached in memory after compilation Using GroovyShell.parse(text)
method.
Is it possible to compile these script only once and keep binary classes on disk/database? The following code would store binary classes in /tmp
;
CompilerConfiguration compilerConfiguration=new CompilerConfiguration();
compilerConfiguration.setTargetDirectory("/tmp/");
GroovyShell shell=new GroovyShell(compilerConfiguration);
shell.parse("println 'foo';","myScript1");
shell.parse("println 'bar';","myScript2");
After running this code i can see myScript1.class
and myScript2.class
in /tmp/
directory, but trying to use above code to load classes AFTER application restart (so there would be no need for recompilation) fails:
CompilerConfiguration compilerConfiguration=new CompilerConfiguration();
compilerConfiguration.setTargetDirectory("/tmp/");
GroovyShell shell=new GroovyShell(compilerConfiguration);
Class clazz=shell.getClassLoader().loadClass("myScript1");
From the source code of GroovyClassLoader
i do not see any way of loading binary classes other than defineClass(java.lang.String, byte[])
method, which gives a following exception when trying to load classes:
Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value 2901213189 in class file myScript1
Is there any other way of directly loading compiled groovy classes?
我弄清楚了,只需为GroovyShell
构造函数提供具有相同目录的URLClassLoader
GroovyShell
正常工作。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.