How can I create an instance of a non-static inner class using reflection? I have inner class name and reference to outer instance.

Dmitri Paltchoun

Ok, I've got It! But does anybody know, whether it is so specified?

import java.lang.reflect.*;
public class Outer{
 public class Inner{}

 public static void main(String[] arg){
   Outer  ou=new Outer();
     Object ob=getInner(ou,"Outer$Inner");
   }catch(Throwable e){e.printStackTrace();}

 public static Object getInner(Object outerRef,String classname)throws Throwable{
   Class innerClass = Class.forName(classname);
   Object[] initArgs = new Object[]{ outerRef };
   Class[] paramTypes =  new Class[]{ outerRef.getClass() };
   Constructor innerConstr = innerClass.getConstructor( paramTypes );
   return innerConstr.newInstance( initArgs );
0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact