Groovy,嵌入在Java中,回调Java
发布时间:2020-12-14 16:22:51 所属栏目:大数据 来源:网络整理
导读:我知道我必须做一些事情,因为脑力死亡这个不能正常工作,但我处于一种情况,我想动态地将行为加载到正在运行的服务器中.我选择groovy作为我的工具来做到这一点.该行为需要引用服务器类路径上的类,例如我的模型对象以及Freemarker等第三方库. 我把这个愚蠢的POC
我知道我必须做一些事情,因为脑力死亡这个不能正常工作,但我处于一种情况,我想动态地将行为加载到正在运行的服务器中.我选择groovy作为我的工具来做到这一点.该行为需要引用服务器类路径上的类,例如我的模型对象以及Freemarker等第三方库.
我把这个愚蠢的POC聚集在一起,以显示可行性.我无法获得groovy脚本来解析Java类“ThingyDoodle”和“Fooable”,尽管事实上我将GroovyClassPath的父类路径设置为我当前的. public class GroovyTest { public static void main ( String [ ] argv ) throws Throwable { // Setting parent classloader! // also tried plain old "GroovyTest.class.getClassLoader()" as well GroovyClassLoader gcl = new GroovyClassLoader ( Thread.currentThread().getContextClassLoader() ) ; String src = "class Arf implements Fooable { public String foo ( ) { return new ThingyDoodle().doStuff('Arf');}}" ; Class clazz = gcl.parseClass(src,"AppleSauce.groovy"); Object aScript = clazz.newInstance(); Fooable myObject = (Fooable) aScript; System.out.println ( myObject.foo() ) ; } public static interface Fooable { public String foo ( ) ; } public static class ThingyDoodle { public String doStuff ( String input ) { return "Hi Worlds" ; } } } 我到底做错了什么? Exception in thread "main" org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: AppleSauce.groovy: 1: unable to resolve class Fooable @ line 1,column 1. class Arf implements Fooable { public String foo ( ) { return new ThingyDoodle().doStuff('Arf');}} ^ AppleSauce.groovy: 1: unable to resolve class ThingyDoodle @ line 1,column 63. ublic String foo ( ) { return new Thingy ^ 解决方法
您的代码中的问题是找不到Fooable接口和ThingyDoodle类,因为它们都是内部类,需要使用包含类名称进行限定,即GroovyTest.我在嵌入式脚本中限定了两个名称(并修复了脚本周围的引号),并按预期运行.
import groovy.lang.GroovyClassLoader; public class GroovyTest { public static void main ( String [ ] argv ) throws Throwable { // Setting parent classloader! // also tried plain old "GroovyTest.class.getClassLoader()" as well GroovyClassLoader gcl = new GroovyClassLoader ( Thread.currentThread().getContextClassLoader() ) ; String src = "class Arf implements GroovyTest.Fooable { " + "public String foo ( ) { " + "return new GroovyTest.ThingyDoodle().doStuff('Arf');}}" ; Class clazz = gcl.parseClass(src,"AppleSauce.groovy"); Object aScript = clazz.newInstance(); Fooable myObject = (Fooable) aScript; System.out.println ( myObject.foo() ) ; } public static interface Fooable { public String foo ( ) ; } public static class ThingyDoodle { public String doStuff ( String input ) { return "Hi Worlds" ; } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |