Outer.javapackage ref;

 

public class Outer

{

        public Outer()

        {

                System.out.println("Outer()");

        }

 

        public class Inner

        {

                public Inner()

                {

                        System.out.println("Inner()");

                }

 

                public void innerM()

                {

                        System.out.println("Inner's m()");

                }

 

                public String toString()

                {

                        return "Inner's toString()";

                }

        }

}

复制代码测试类package ref;

 

import java.lang.reflect.Constructor;

import java.lang.reflect.Method;

 

public class TestInnerRef

{

        public static void main(String[] args) throws Exception

        {

//                method1();

                method2();

        }

        /*

         * 利用类名Outer$Inner得到内部类的类对象

         * 直接newInstance会抛出java.lang.InstantiationException: ref.Outer$Inner

         * 构造成员内部类对象需要外部类对象,所以这样使用有问题

         */

        public static void method1() throws Exception

        {

                Class c = Class.forName("ref.Outer$Inner");

                System.out.println(c.getName());

                Object o = c.newInstance();

        }

       

        public static void method2() throws Exception

        {

                Class outc = Class.forName("ref.Outer");

                Object outer = outc.newInstance();

               

                Class[] incs = outc.getClasses();

                for (Class inc : incs)

                {

                        System.out.println(inc.getName());

                        Constructor con = inc.getConstructor(new Class[]{outc});

                        Object inner = con.newInstance(outer);

                        System.out.println(inner);

                        Method m = inc.getMethod("innerM", new Class[]{});

                        m.invoke(inner, new Object[]{});

                }

        }

}