0

How do you create an inner class object with reflection? Both Inner and Outer classes have default constructors that take no parameters

Outer class {
    Inner class{
   }
    public void createO() {
        Outer.Inner ob = new Inner ();//that works
        Inner.class.newInstance(); //<--why does this not compile?
   }
}

1 Answer 1

2

"If the constructor's declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance; see section 15.9.3 of The Java™ Language Specification."

That means you can never construct an inner class using Class.newInstance; instead, you must use the constructor that takes a single Outer instance. Here's some example code that demonstrates its use:

class Outer {
    class Inner {
        @Override
        public String toString() {
            return String.format("#<Inner[%h] outer=%s>", this, Outer.this);
        }
    }

    @Override
    public String toString() {
        return String.format("#<Outer[%h]>", this);
    }

    public Inner newInner() {
        return new Inner();
    }

    public Inner newInnerReflect() throws Exception {
        return Inner.class.getDeclaredConstructor(Outer.class).newInstance(this);
    }

    public static void main(String[] args) throws Exception {
        Outer outer = new Outer();
        System.out.println(outer);
        System.out.println(outer.newInner());
        System.out.println(outer.newInnerReflect());
        System.out.println(outer.new Inner());
        System.out.println(Inner.class.getDeclaredConstructor(Outer.class).newInstance(outer));
    }
}

(Note that in standard Java terminology, an inner class is always non-static. A static member class is called a nested class.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.