我真的是groovy脚本的新手但是在一些教程之后我尝试使用 GroovyClassLoader
的 parseClass()
方法在我的java代码中动态加载一些groovy类 . 我写了一些片段,它对我来说很好 . 问题是我不清楚我的视图之外的groovy引擎是什么以及这些脚本是如何编译的?
是否有新的类被压缩并加载到jvm中?或者我的应用程序是否使用了一些缓存来源?
这是我要解析的类:
private static class MyScript {
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("public class SomeClass\n");
builder.append("{\n");
builder.append("Some code...").append("\n");
builder.append("}\n");
return builder.toString();
}
我用 build()
加载它如下:
private Class MyGroovyBuilder {
private Script script = new Script();
public String build() throws TemplateCompilationException
//
String groovyText = script.toString();
//
CompilerConfiguration config = new CompilerConfiguration();
//
byte[] bytes;
try
{
bytes = groovyText.getBytes(config.getSourceEncoding());
}
catch (UnsupportedEncodingException e)
{
throw new TemplateCompilationException(e, groovyText);
}
//
InputStream in = new ByteArrayInputStream(bytes);
GroovyCodeSource gcs = new GroovyCodeSource(in, "SomeName", "/groovy/shell");
GroovyClassLoader loader = new
GroovyClassLoader(Thread.currentThread().getContextClassLoader(), config);
Class<?> scriptClass;
try
{
scriptClass = loader.parseClass(gcs, false);
}
catch (CompilationFailedException e)
{
throw new GroovyCompilationException(e, "SomeName", groovyText);
}
catch (ClassFormatError e)
{
throw new GroovyCompilationException(e, "SomeName", groovyText);
}
return scriptClass.getName();
}
任何澄清都非常受欢迎 .
BR .
1 回答
加载类后,它出现在您的类加载器中,并且可以像任何其他类一样访问 .
有一个简单的教程[here],它展示了如何从字符串加载类 .
在最简单的情况下,您可以加载类,并保持它的Class对象,使用它来动态创建对象 . 对于字段访问或方法调用,您可以依赖Groovy动态特性 .
在场景后面没有"cached source"或类似的东西,你可以忘记,从你的课程加载 . 您还可以缓存已编译的类,并将它们保存在某处,如[here]所述 . 如果您需要经常加载相同的类,它将大大提高性能 .
但是在主题中挖掘会更好,因为动态类加载是高级Java / Groovy技术,它是链式类加载器的整个基础结构,所以最好引用它们的文档 .
以下链接可能会有所帮助 .
http://javarevisited.blogspot.ru/2012/12/how-classloader-works-in-java.html
How to use URLClassLoader to load a *.class file?