我知道我必须做一些事情,因为脑力死亡这个不能正常工作,但我处于一种情况,我想动态地将行为加载到正在运行的服务器中.我选择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" ;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。