1. 程式人生 > >反射獲得內部類

反射獲得內部類

1.反射呼叫類方法用invoke即可,但是內部類的話還是需要琢磨一番
2.呼叫invoke方法需要獲得引數,即類例項,通過建構函式來獲得

先寫個大小類:

/**
 * Created by garfield on 2016/11/18.S
 */
public class OuterClass {
    public void print(){
        System.out.println("i am Outer class");
    }
     class InnerClass{
         void print2(){
            System.out.println("i am inner class");
        }
    }
}

呼叫:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
 * Created by garfield on 2016/11/18.
 */
public class TestClass {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class c = Class.forName("com.newland.sri.utep.OuterClass");
        //通過方法名獲取方法
        Method method = c.getDeclaredMethod("print");
        //呼叫外部類方法
        method.invoke(c.newInstance());
        //內部類需要使用$分隔
        Class c2 = Class.forName("com.newland.sri.utep.OuterClass$InnerClass");
        Method method2 = c2.getDeclaredMethod("print2");
        //通過建構函式建立例項,如果沒有重寫構造方法則不管是不是獲取已宣告構造方法,結果是一樣的
        method2.invoke(c2.getDeclaredConstructors()[0].newInstance(c.newInstance()));
    }
}

2.如果出現了不同情況,也就是構造方法被重寫了,因為獲取的例項不同,其構造方法也不同,所以要新增上引數
更改一下類:
/**
 * Created by garfield on 2016/11/18.S
 */
public class OuterClass {
    public void print(){
        System.out.println("i am Outer class");
    }
     class InnerClass{
         InnerClass(String a){
             
         }
         void print2(){
            System.out.println("i am inner class");
        }
    }
}

中間重寫了內部類的構造方法,這時候做相應更改:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
 * Created by garfield on 2016/11/18.
 */
public class TestClass {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class c = Class.forName("com.newland.sri.utep.OuterClass");
        //通過方法名獲取方法
        Method method = c.getDeclaredMethod("print");
        //呼叫外部類方法
        method.invoke(c.newInstance());
        //內部類需要使用$分隔
        Class c2 = Class.forName("com.newland.sri.utep.OuterClass$InnerClass");
        Method method2 = c2.getDeclaredMethod("print2");
        //這時候不能用c2.getConstructors(),已經不存在未宣告的構造方法,所以這樣寫是錯的
        method2.invoke(c2.getDeclaredConstructors()[0].newInstance(c.newInstance(),"a"));
    }
}

結果:

i am Outer class
i am inner class