Why is it thrown java.lang.InstantiationException?

Viewed 1169

Look at following code:

public class Outer {
    public static void main(String[] args) throws Exception {
        new Outer().greetWorld();
    }

    private void greetWorld() throws Exception {
        System.out.println(Inner.class.newInstance());
    }

    public class Inner {
        public Inner () {}
        public String toString(){
            return "HelloWorld";
        }
    }
}

Why is it thrown java.lang.InstantiationException ?
After all, nested class Inner has nully constructor. Can someone explain it?

2 Answers

The [implicit] first argument in an inner's class' constructor is a reference to its enclosing class. When calling it via reflection, you need to explicitly provide it:

private void greetWorld() throws Exception {
    System.out.println(Inner.class.getConstructors()[0].newInstance(this));
}

Your class Inner needs to be instantiated, one solution would be to declare it static.

static class Inner {
    public Inner () {}
    public String toString(){
        return "HelloWorld";
    }
}
Related