本文介绍了在运行时从Java编译和使用Groovy类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个应用程序,我想让其扩展,让用户在Groovy中定义类,最终实现一些接口。 关键方面是在运行时解释/编译。也就是说我需要我的应用程序采取 .groovy 并编译它。 然后,当然,我的应用程序应该能够实例化该类。 我看到两个解决方案: 1)在应用程序运行时编译,将类放在classpath上,然后加载类,假装他们总是在那里。 2)一些更聪明的方式 - 调用编译器API和一些类加载魔术让我的系统类加载器看到它们。 >解决方案查看在Java中动态加载和运行Groovy代码 获取类Loader 加载类 : .groovy 编译为 .class 字节码,解析类会给你一个 instanceof code> Class 。现在它变成所有JAVA世界,只有区别,一旦你在实例化之后获得 GroovyObject ,你就可以按需调用方法。 编辑:所以它包含在这里: InputStream groovyClassIS = GroovyCompiler.class .getResourceAsStream /org/jboss/loom/tools/groovy/Foo.groovy); GroovyClassLoader gcl = new GroovyClassLoader(); Class clazz = gcl.parseClass(groovyClassIS,SomeClassName.groovy); Object obj = clazz.newInstance(); IFoo action =(IFoo)obj; System.out.println(action.foo()); 和 package org.jboss.loom.migrators.mail; import org.jboss.loom.tools.groovy.IFoo; public class Foo implements IFoo { public String foo(){ returnFoooooooooo Action! } } I have an app which I'd like to make extensible by letting users define classes in Groovy, eventually implementing some interfaces.The key aspect is that it should be interpreted/compiled at runtime. I.e. I need my app to take the .groovy and compile it. Doing it during boot is ok.Then, of course, my app should be able to instantiate that class.I see two solutions:1) Compile while the app runs, put the classes somewhere on classpath, and then just load the classes, pretending they were always there.2) Some smarter way - calling a compiler API and some classloading magic to let my system classloader see them.How would I do option 2)?Any other ideas? 解决方案 Have a look at Dynamically loading and running Groovy code inside JavaGet class LoaderLoad classInstantiate class.Beauty:-Since .groovy compiles to .class bytecode, parsing the class would give you an instanceof Class. Now it becomes all JAVA world, only difference, once you get hold of GroovyObject after instantiatiation, you play around invoking methods on demand.Edit: Just so it's contained here:InputStream groovyClassIS = GroovyCompiler.class .getResourceAsStream("/org/jboss/loom/tools/groovy/Foo.groovy");GroovyClassLoader gcl = new GroovyClassLoader();Class clazz = gcl.parseClass(groovyClassIS, "SomeClassName.groovy");Object obj = clazz.newInstance();IFoo action = (IFoo) obj;System.out.println( action.foo());andpackage org.jboss.loom.migrators.mail;import org.jboss.loom.tools.groovy.IFoo;public class Foo implements IFoo { public String foo(){ return "Foooooooooo Action!"; }} 这篇关于在运行时从Java编译和使用Groovy类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-10 21:58