Groovy:将动态编译的类写入光盘 [英] Groovy: writing dynamically compiled class to disc

查看:61
本文介绍了Groovy:将动态编译的类写入光盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my app I need to compile classes / scripts in runtime.

作为 Class :

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

或作为 closure :

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

两种方式都像魅力一样工作.

Both ways work like charm.

现在,我需要能够将已编译的类/脚本写入某些持久性存储(disc),然后在不从头进行编译的情况下将它们还原回去.

Now I need to be able to write the compiled classes/scripts to some persistant storage (disc) and later restore them back without compiling from scratch.

这怎么办?

推荐答案

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

For those who might be interested, this is my programming kata:

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
  }

}

这篇关于Groovy:将动态编译的类写入光盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆