简体   繁体   中英

How do I assign instance of Groovy class to variable in Java class

I have a Groovy class like this:

package com.hello

class MyClass {
    def myMethod() { println "hello" }
}

And I want to use this class in a Java class:

package com.hello

public class OtherClass {
    MyClass myc;

    public void myOtherMethod {
        myc.myMethod(); // <-- Raises NullPointerException
    }
}

When I run this code, it throws a NullPointerException because myc is null. When I try this:

...
MyClass myc = new MyClass();
public void myOtherMethod {
    myc.myMethod(); // <-- Raises NullPointerException
}
...

I still get a NullPointerException . How do I use this groovy class in my java class?

    package com.hello

    public class OtherClass 
    {
         MyClass myc=new MyClass();

        public void myOtherMethod() {
            myc.myMethod();
        }
    }

Where OtherClass is Java should work just fine regardless of MyClass being groovy or Java.

If you are still getting an NPE with this code on the call to myMethod() then you have a build problem.. Try the following:

  • recompile your groovy code into a class
  • recompile the java to a class, make sure your groovy class is available to javac at the time.
  • If you run with java, be SURE that the groovy-all jar is in your classpath (If you run it with groovy this will be automatic)

The easiest way not to deal with build problems (or put off dealing with them) is to code in eclipse with the Groovy plugin and run straight from Eclipse, that should always work.

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