Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I construct a (non-static) Java inner class from Groovy

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]?

like image 381
james.cookie Avatar asked Jan 16 '15 09:01

james.cookie


People also ask

How do you instantiate a non-static inner class?

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.

What is non-static inner class in Java?

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.

Do inner classes need static?

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.


2 Answers

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.

like image 118
Rob Fletcher Avatar answered Nov 01 '22 16:11

Rob Fletcher


try this

    A a = new A();
    System.out.println(new B(a, "test")); //crazy syntax!
like image 3
Evgeniy Dorofeev Avatar answered Nov 01 '22 14:11

Evgeniy Dorofeev