使用Java反射,您可以檢查類的方法并在運(yùn)行時(shí)調(diào)用它們凭迹。 這是通過Java類java.lang.reflect.Method完成的摊聋。 本文將更詳細(xì)地介紹Java方法對(duì)象。
獲取方法對(duì)象
Method類是從Class對(duì)象中獲得的璧瞬。 這里是一個(gè)例子:
Class aClass = ...//obtain class object
Method[] methods = aClass.getMethods();
Method []數(shù)組對(duì)于在該類中聲明的每個(gè)公用方法都將有一個(gè)Method實(shí)例户辫。
如果您知道要訪問的方法的確切參數(shù)類型,則可以這樣做嗤锉,而不是獲取數(shù)組的所有方法渔欢。 這個(gè)例子返回一個(gè)名為“doSomething”的公共方法,該方法以String為參數(shù):
Class aClass = ...//obtain class object
Method method =
aClass.getMethod("doSomething", new Class[]{String.class});
如果沒有方法匹配給定的方法名稱和參數(shù)瘟忱,在這種情況下String.class奥额,拋出一個(gè)NoSuchMethodException。
如果您嘗試訪問的方法不帶參數(shù)访诱,請(qǐng)將null作為參數(shù)類型數(shù)組垫挨,如下所示:
Class aClass = ...//obtain class object
Method method =
aClass.getMethod("doSomething", null);
方法參數(shù)和返回類型
你可以閱讀一個(gè)給定的方法是這樣的參數(shù):
Method method = ... // obtain method - see above
Class[] parameterTypes = method.getParameterTypes();
你可以像這樣訪問一個(gè)方法的返回類型:
Method method = ... // obtain method - see above
Class returnType = method.getReturnType();
使用方法對(duì)象調(diào)用方法 invoke
你可以調(diào)用像這樣的方法:
//get method that takes a String as argument
Method method = MyObject.class.getMethod("doSomething", String.class);
Object returnValue = method.invoke(null, "parameter-value1");
null參數(shù)是要調(diào)用該方法的對(duì)象。 如果方法是靜態(tài)的触菜,則提供null而不是對(duì)象實(shí)例九榔。 在這個(gè)例子中,如果doSomething(String.class)不是靜態(tài)的涡相,則需要提供一個(gè)有效的MyObject實(shí)例而不是null;
Method.invoke(Object target哲泊,Object ... parameters)方法接受可選數(shù)量的參數(shù),但是您必須為要調(diào)用的方法中的每個(gè)參數(shù)提供一個(gè)參數(shù)漾峡。 在這種情況下攻旦,這是一個(gè)采取字符串的方法,所以必須提供一個(gè)字符串生逸。
實(shí)戰(zhàn)
package com.reflection.detail;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by Fant.J.
* 2018/2/7 15:04
*/
public class Reflection_Methods {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//獲取所有的共有方法
Class aClass = People.class;
Method [] methods = aClass.getMethods();
//獲取知道方法名稱和參數(shù) 的方法, 如果沒有參數(shù)牢屋,則傳入null
Method method = aClass.getMethod("setName", String.class);
Method method1 = aClass.getMethod("getName",null);
//根據(jù)method獲取參數(shù)類型
method.getParameterTypes();
//根據(jù)method獲取返回值類型
method.getReturnType();
/**
* 使用反射來調(diào)用方法且预。如果方法是靜態(tài)方法,則不需要實(shí)例該對(duì)象烙无。
* 因?yàn)槲疫@里這個(gè)方法不是靜態(tài)的锋谐。所以我實(shí)例化People對(duì)象
* 仔細(xì)看看method和method1 是啥。代表了啥
*/
People people = new People();
method.invoke(people,"Fant.J");
Object obj = method1.invoke(people,null);
System.out.println(obj);
}
}
結(jié)果
Fant.J
項(xiàng)目代碼:github鏈接