简体   繁体   中英

Passing a groovy object to a Java method

I'm creating an object in java and setting it as a variable in 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() .

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. I created from a java class. Can I not pass groovy-created objects to a java class I set as a variable?

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. By renaming the file or variable, I could pass down the object without any problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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