本帖最后由 迷失的独白 于 2014-8-29 21:12 编辑
- package mystudyexercisejava;
- import java.lang.reflect.Modifier;
-
- public class ReflectInnerClassTest {
-
- public static void main(String args[]){
- ReflectInnerClass ric=new ReflectInnerClass();
- try {
- reflectInnerClass(ric);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- private static void reflectInnerClass(ReflectInnerClass ric) throws Exception {
- Class clazz=ric.getClass();
- Class classes[]=clazz.getDeclaredClasses();
- for(Class c:classes){//对成员内部类进行反射
- int i=c.getModifiers();
- String s=Modifier.toString(i);
- if(s.contains("static"))//静态内部类的处理
- c.getConstructor().newInstance();
- else//实例内部类的处理
- c.getConstructor(ric.getClass()).newInstance(ric);
- }
- Runnable r=(Runnable)(clazz.getField("ta").get(ric));
- r.run();
- }
- }
- class ReflectInnerClass {
- public Runnable ta=new Runnable(){
- public void run(){
- System.out.println("匿名内部类中的方法被执行了");
- }
- };
- class Innerc{
- public Innerc(){
- System.out.println("Inner3类被实例化了");
- }
- }
- private class Innerb{
- public Innerb(){
- System.out.println("Inner2类被实例化了");
- }
- }
- public static class Innerd{
- public Innerd(){
- System.out.println("Inner4类被实例化了");
- }
- }
- public class Innera{
- public Innera(){
- System.out.println("Inner1类被实例化了");
- }
- }
- }
复制代码
c.getConstructor(ric.getClass()).newInstance(ric); 这句话
|
|