Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Groovy绑定:无法使用类';custompackage.CustomClass';到类';custompackage.CustomClass';_Groovy - Fatal编程技术网

Groovy绑定:无法使用类';custompackage.CustomClass';到类';custompackage.CustomClass';

Groovy绑定:无法使用类';custompackage.CustomClass';到类';custompackage.CustomClass';,groovy,Groovy,使用Groovy绑定从主控制器执行脚本并尝试传递自定义对象,我得到了标题中提到的错误 Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'custompackage.CustomClass@60099951' with class 'custompackage.CustomClass' to class 'custompackage.CustomClass' 以下是相

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

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
}
为了在IDE中自动完成,我在开始时定义了
CustomClass t
。当以def t
def运行时,它工作正常

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

错误发生在
t=test

为什么Groovy试图将同一类型的对象强制转换为它的类型,但失败了?是否有一个修复程序仍然允许我保留静态类型的
t


谢谢

控制器.groovy中的
custompackage.CustomClass
似乎与
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
作为参数。也许这就是路,但我不确定。

太棒了!我没有注意到。我假设@number与对象的实例有关。切换到使用
GroovyShell
,因为这适合我的需要。多谢!