If I have a class with an inner class like this:
public class A {
class B { //note, no modifier on class or constructor
B(String c) {System.out.println(c);}
}
}
From Java (in the same package) I can do this:
public class C {
public static void main(String[] args) {
A a = new A();
System.out.println(a. new B("test")); //crazy syntax!
}
}
But in Groovy, that doesn't work. So how do I construct a new B [from a groovy class in the same package]?
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.
A non-static nested class is a class within another class. It has access to members of the enclosing class (outer class). It is commonly known as inner class . Since the inner class exists within the outer class, you must instantiate the outer class first, in order to instantiate the inner class.
Inner classes are non-static member classes, local classes, or anonymous classes. In this tutorial you'll learn how to work with static member classes and the three types of inner classes in your Java code.
I got it to work like this:
def a = new A()
A.B.newInstance(a, "foo")
And also like this:
def a = new A()
new A.B(a, "foo")
If the Java code is under your control rather than being an external library I'd far rather use a factory method, though.
try this
A a = new A();
System.out.println(new B(a, "test")); //crazy syntax!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With