gpt4 book ai didi

java - Groovy,嵌入Java,回调Java

转载 作者:搜寻专家 更新时间:2023-11-01 02:30:38 27 4
gpt4 key购买 nike

我知道我必须做一些脑残愚蠢的事情才能使它不起作用,但我处于一种情况,我想将行为动态加载到正在运行的服务器中。我选择 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 接口(interface)和 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" ;
}
}


}

关于java - Groovy,嵌入Java,回调Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10324199/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com