Groovy: 将动态编译的 class 写入光盘

Groovy: writing dynamically compiled class to disc

在我的应用程序中,我需要在运行时编译 类 / 脚本。

作为 Class:

Class<? extends LoginAdapter> clazz = groovyClassLoader.loadClass name
LoginAdapter la = clazz.newInstance id, logo

或作为 Closure:

Closure action = groovyShell.evaluate( script, name ) as Closure

两种方式都很有魅力。

现在我需要能够将编译后的 classes/scripts 写入一些持久存储(光盘),然后在不从头编译的情况下恢复它们。

如何做到这一点?

对于那些可能感兴趣的人,这是我的编程套路:

class Base {
  String answer() { null }
  String question() { 'WHAT IS.... ?' }
}
class ClazzSpec extends Specification {

  def "test compile"() {
    given:
    String packageName = 'some.pckg'
    String body = """
package $packageName

class SomeClass extends Base {
  Closure cl = { a -> println a }
  @Override String answer(){ '42' }
  String json( m ){ JsonOutput.toJson( m ) }
  String longOne( int times ){ 
    times.times{ sleep 100 }
    'done'
  }
}
"""

    CompilerConfiguration cc = new CompilerConfiguration( targetDirectory:new File( './out' ) )
    ImportCustomizer imp = new ImportCustomizer()
    imp.addStarImports 'groovy.json', Base.package.name
    cc.addCompilationCustomizers imp, new ASTTransformationCustomizer( value:1, TimedInterrupt )

    new Compiler( cc ).compile packageName + '.SomeClass', body

    File base = new File( './out' )

    GroovyClassLoader gcl = new GroovyClassLoader()
    gcl.addClasspath './out'
    Class clazz = gcl.loadClass 'some.pckg.SomeClass'

    when:
    def inst = clazz.newInstance()

    then:
    inst.question() == 'WHAT IS.... ?'
    inst.answer() == '42'
    inst.json( [ q:42 ] ) == '{"q":42}'
    inst.longOne( 2 ) == 'done'

    when:
    inst.longOne 11

    then:
    thrown TimeoutException
  }

}