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