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:
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.