Groovy绑定:无法将类’custompackage.CustomClass’的对象强制转换为类’custompackage.CustomClass’

使用Groovy Binding从主控制器执行脚本并尝试传递自定义对象,我得到标题中提到的错误.

Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'custompackage.CustomClass@60099951' with class 'custompackage.CustomClass' to class 'custompackage.CustomClass'

这是相关的代码:

// Controller.groovy
import custompackage.CustomClass
CustomClass test = new CustomClass()

def binding = new Binding()
def engine = new GroovyScriptEngine('./src')

binding.setProperty("test", test)

engine.run("CustomScript.groovy", binding)

上面运行的文件:

// CustomScript.groovy
import custompackage.CustomClass
CustomClass t 

if(!binding.variables.containsKey("test")){
    t = new CustomClass()
} else {        
    t = test
}

我在开始时定义了CustomClass,以便在IDE中自动完成.当作为def t运行时,它工作正常.

由于异常(以及对象的进一步打印),我知道对象正在正确传递

t = test时发生错误

为什么Groovy试图将类型相同的对象转换为它的类型,然后没有这样做?还有一个解决方案仍然允许我保持静态类型的t?

谢谢!

最佳答案 似乎custompackage.Controller.groovy中的自定义类与CustomScript.groovy中的不同.

我使用调试器检查了CustomScript.groovy中的类实例,发现了一些有趣的东西:

def a = CustomClass.class // Debugger: a={Class@1499} "class custompackage.CustomClass"
def b = test.class        // Debugger: b={Class@1187} "class custompackage.CustomClass"

当在Controller.groovy中使用GroovyShell而不是GroovyScriptEngine时,我得到:

def a = CustomClass.class // Debugger: a={Class@1185} "class custompackage.CustomClass"
def b = test.class        // Debugger: b={Class@1185} "class custompackage.CustomClass"

并且赋值t = test无错误地工作.

使用GroovyShell的Controller.groovy文件如下所示:

// Controller.groovy
import custompackage.CustomClass
CustomClass test = new CustomClass()

def binding = new Binding()
def shell = new GroovyShell(binding)

binding.setProperty("test", test)

shell.evaluate(new File("CustomScript.groovy"))

我查看了GroovyScriptEngine的文档,发现了一个以ClassLoader为参数的构造函数.也许这是要走的路,但我不确定.

点赞