简体   繁体   English

将Groovy对象传递给Java方法

[英]Passing a groovy object to a Java method

I'm creating an object in java and setting it as a variable in GroovyShell. 我在Java中创建一个对象,并将其设置为GroovyShell中的变量。

// in java file, create class and shell
//
class Foo {
   void addSomething(Bar bar) { ... }
}

shell.setVariable("foo", new Foo())

In groovy I create an new class that extends from Bar and try to call addSomething() . 在groovy中,我创建了一个从Bar扩展的新类,并尝试调用addSomething()

class MyBar extends Bar
{
    ...
}

foo.addSomething(new MyBar())

This fails with something like: 失败的原因是:

groovy.lang.MissingMethodException: No signature of method: static foo.addSomething() is applicable for argument types: (MyBar) values: [MyBar@4ba7aa7]

Maybe the static part is throwing me off, but I don't understand the error. 也许静态部分让我失望了,但我不明白该错误。 I thought it may have to do with passing a groovy-created subclass to addSomething, but I also tried passing an object. 我认为这可能与将Groovy创建的子类传递给addSomething有关,但我也尝试传递一个对象。 I created from a java class. 我是从Java类创建的。 Can I not pass groovy-created objects to a java class I set as a variable? 我不能将groovy创建的对象传递给设置为变量的java类吗?

I found the problem was the variable name I was passing to groovy matched the file name and the file name was stomping over the variable. 我发现问题是我传递给groovy的变量名与文件名匹配,并且文件名踩了变量。 By renaming the file or variable, I could pass down the object without any problems. 通过重命名文件或变量,我可以毫无问题地传递对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM