invoke 主要是用來調用某個類中的方法的,但是他不是通過當前類直接去調用而是通過反射的機制去調用。
在這之前我們先新建一個實體類,一會會用到。
public class TestMode {
private static final String TAG = "TestMode";
private int age;
String name;
int length;
public TestMode() {
}
public TestMode(int age, String name, int length) {
this.age = age;
this.name = name;
this.length = length;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private void testReflect(String msg) {
System.out.println(msg);
}
@Override
public String toString() {
return "TestMode{" +
"age=" + age +
", name='" + name + '\'' +
", length=" + length +
'}';
}
}
然後我們上個測試類:
public class ReflectTest {
public static void main(String args[]) {
TestMode testMode = new TestMode(30, "明", 170);
//獲取class 對象
Class cla = testMode.getClass();
//獲取去類中的所有方法,返回一個method數組
Method[] methods = cla.getDeclaredMethods();
for (Method method : methods) {
method.setAccessible(true);
//獲取當前方法的修飾符參數
int modifiers = method.getModifiers();
//獲取該方法的參數
Class<?>[] types= method.getParameterTypes();
//只調用私有方法,並且參數必須是一個
if (modifiers == Modifier.PRIVATE && types.length==1) {
try {
method.invoke(testMode, "我要開始調用方法了" + method.getName());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
執行結果:
我要開始調用方法了testReflect
1. getDeclaredMethods() 是Class 類的方法,它返回了當前類的所有的方法數組 Method[]數組,
Method是方法相關參數的封裝類。
2. getModifiers() 是method 類中的方法,通過該方法我們可以獲取該方法的修飾符 類如 public 等,
java 中Modifier 類定義了所有的修飾符。
3. getParameterTypes() 是method 類中的方法,通過該方法能夠返回當前方法的所有參數的class[] 數組,並且是順序的。
4. invoke(Object obj, Object... args) 是method 類中的方法,這個方法是一個native 方法
obj: 調用類的實例對象
args:調用發方法的參數,是可變長度的
通過 method.invoke(obj , args ) 可以實現method 方法的調用,並通過args 參數傳參。