Java反射之调用内部类
1. 反射调用默认访问权限的内部类
package com.blueStarWei.invoke; import java.lang.reflect.Method; import com.blueStarWei.invoke.OuterClass.InnerClass; class OuterClass { public void func(){ System.out.println("Outer Class."); } class InnerClass { private String mName; public InnerClass(String mName) { this.mName = mName; } void getName(){ System.out.println("Name is : "+mName); } } } public class OuterInnerClass { public static void main(String[] args) { try { /*通过反射实例化内部类 * 强大之处在于:当内部类私有化(private class InnerClass)时,也可以调用 * */ Class outerClass = Class.forName("com.blueStarWei.invoke.OuterClass"); Class innerClass = Class.forName("com.blueStarWei.invoke.OuterClass$InnerClass"); Method method = innerClass.getDeclaredMethod("getName"); //TODO study it //内部类newInstance的第一个参数必须是外部类实例的引用 method.invoke(innerClass.getDeclaredConstructors()[0].newInstance(outerClass.newInstance(),"Wei"));//Name is : Wei /*常规方法实例化内部类 * 当内部类私有化时,无法通过该方式实例化内部类 * */ OuterClass outerClass1 = new OuterClass(); InnerClass innerClass1 = outerClass1.new InnerClass("David"); innerClass1.getName();//Name is : David } catch (Exception e) { e.printStackTrace(); } } }
2. 反射调用静态内部类
package com.blueStarWei.invoke; import java.lang.reflect.Method; class OuterClass { public void func(){ System.out.println("Outer Class."); } static class InnerClass { private String mName; public InnerClass(String mName) { this.mName = mName; } void getName(){ System.out.println("Name is : "+mName); } } } public class StaticInnerClass { public static void main(String[] args) { try { /*通过反射实例化内部类 */ Class outerClass = Class.forName("com.blueStarWei.invoke.OuterClass"); Class innerClass = Class.forName("com.blueStarWei.invoke.OuterClass$InnerClass"); Method method = innerClass.getDeclaredMethod("getName"); //静态内部类没有持有外部类的引用,不需要传递外部类实例对象的引用 method.invoke(innerClass.getDeclaredConstructors()[0].newInstance("Wei"));//Name is : Wei } catch (Exception e) { e.printStackTrace(); } } }
3. 反射调用匿名内部类
package com.blueStarWei.invoke; class OuterClass { public Runnable runnable = new Runnable() { @Override public void run() { System.out.println("This is InnerClass."); } }; } public class AnonymousInnerClass { public static void main(String[] args) { try { Class outerClass = Class.forName("com.blueStarWei.invoke.OuterClass"); //将匿名内部类当作外部类的成员变量 Runnable runnable = (Runnable) outerClass.getDeclaredField("runnable").get(outerClass.newInstance()); runnable.run(); } catch (Exception e) { e.printStackTrace(); } } }
更多内容,请访问:http://www.cnblogs.com/BlueStarWei