我想要一个带有一些代码的groovy脚本,然后我想将该代码复制到生成的类中的方法。然后在运行时使用该类。
当我运行下面的代码时,我得到ClassNotFoundException
。我该如何解决它,以便我可以创建这个生成的类的对象?
class GenerateClassTest {
public static void main(String[] args) {
String script = ''
CompilerConfiguration compilerConfiguration = new CompilerConfiguration()
compilerConfiguration.addCompilationCustomizers(new MyCompilationCustomizer())
GroovyClassLoader myClassLoader = new GroovyClassLoader()
GroovyShell groovyShell = new GroovyShell(myClassLoader, new Binding(), compilerConfiguration)
groovyShell.evaluate(script)
def newGeneratedClassObj = myClassLoader.loadClass('MyGeneratedClass').newInstance()
}
}
class MyCompilationCustomizer extends CompilationCustomizer {
MyCompilationCustomizer() {
super(CompilePhase.CONVERSION)
}
@Override
void call(SourceUnit source, GeneratorContext context, ClassNode currentClassNode) throws CompilationFailedException {
ClassNode myNewClass = new AstBuilder().buildFromSpec {
classNode('MyGeneratedClass', ClassNode.ACC_PUBLIC) {
classNode Object
interfaces {}
mixins {}
}
}.first()
source.getAST().addClass(myNewClass)
}
}
答案 0 :(得分:1)
而不是
def newGeneratedClassObj = myClassLoader.loadClass('MyGeneratedClass').newInstance()
使用评估脚本的GroovyShell
:
def newGeneratedClassObj = groovyShell.getClassLoader().loadClass('MyGeneratedClass').newInstance()