Instantiating an inner class using reflection

A static inner class can be instantiated without the need of an instance of the outer class.

Main.java:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         InnerClass ic = (InnerClass) InnerClass.class.newInstance();
         ic.test();
      }
      catch(Exception e) {
         System.err.println(e);
      }
   }
 
   static class InnerClass {
      public void test() {
         System.out.println("Method test called!");
      }
   } 
}

You need an instance of the outer class to instantiate a non-static inner class. Just specify it before the new operator.

An inner class will have an implicit constructor taking a parameter that takes a parameter to the enclosing object. So you need to create a Constructor object and invoke it providing it with the instance of the outer object.

Main.java:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) {
      Main main = new Main();
 
      try {
         Class inner = Class.forName("Main$InnerClass");
         Constructor constructor = inner.getConstructor(new Class[]{ main.getClass() });
         InnerClass ic = (InnerClass) constructor.newInstance(new Object[] { main });
         ic.test();
      }
      catch(Exception e) {
         System.err.println(e);
      }
   }
 
   public class InnerClass { 
      public void test() {
         System.out.println("Method test called!");
      }
   } 
}