动态创建Groovy类

动态创建Groovy类,第1张

动态创建Groovy类

我已经或多或少地能够通过使用GroovyClassLoader和SimpleTemplateEngine使其工作。这是代码:

class ClassBuilder {    GroovyClassLoader loader    String name    Class cls    def imports    def fields    def methods    def ClassBuilder(GroovyClassLoader loader) {        this.loader = loader        imports = []        fields = [:]        methods = [:]    }    def setName(String name) {        this.name = name    }    def addimport(Class importClass) {        imports << "${importClass.getPackage().getName()}" +     ".${importClass.getSimpleName()}"    }    def addField(String name, Class type) {        fields[name] = type.simpleName    }    def addMethod(String name, Closure closure) {        methods[name] = closure    }    def getCreatedClass() {        def templateText = '''<%imports.each {%>import $itn <% } %> class $name{<%fields.each {%>    $it.value $it.key n<% } %>}'''        def data = [name: name, imports: imports, fields: fields]        def engine = new groovy.text.SimpleTemplateEngine()        def template = engine.createTemplate(templateText)        def result = template.make(data)        cls = loader.parseClass(result.toString())        methods.each { cls.metaClass."$it.key" = it.value        }        return cls    }}

这是我如何使用它动态创建类的示例

import java.util.Calendardef builder = new ClassBuilder(this.class.classLoader)builder.setName("MyClass");builder.addimport(Calendar)builder.addField('field1', Integer)builder.addField('field2', Integer)builder.addMethod('sum') { field1 + field2 }builder.addMethod('product') { field1 * field2 }builder.addMethod('testCalendar') {    println Calendar.getInstance().getTime()}Class myClass = builder.getCreatedClass()def myInstance = myClass.newInstance()myInstance.field1 = 1myInstance.field2 = 2println myInstance.sum()println myInstance.product()myInstance.setField2(1500)println myInstance.getField2()myInstance.testCalendar()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5427147.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存