-2

I have the following School class which contains a inner Office class:

class School {
    class Offcie {
        Office() {
          ...
        }
    }
}

In another place, I get an instance of School named mySchool.

The normal way to instantiate Office is :

School mySchool = new School();
Office myOffice = mySchool.new Office();

But how to use java reflection to get an instance of Office by using mySchool instance ?

user842225
  • 5,445
  • 15
  • 69
  • 119

1 Answers1

0

Get a reference to the Office parameterless Constructor and invoke it with a single argument, the School instance.

Constructor<Office> constructor = Office.class.getDeclaredConstructor(School.class);
Office office = constructor.newInstance(new School()); // or your instance

This is explained in the javadoc

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • But I am not able to access Office class directly, the 'Office' can not be found. I can only find by Class.forName("com.xx.yy.School$Office"); – user842225 Apr 28 '14 at 14:46
  • @user842225 Use `Class.forName`. It returns a `Class` object you can use. If you're getting a `ClassNotFoundException`, you have a different problem. – Sotirios Delimanolis Apr 28 '14 at 14:48