一、概述
Java getMethod是一個很實用的反射方法,能夠獲取指定類的指定方法。在一些需要動態調用方法的場景,getMethod可以大展神威,它可以通過字元串動態調用類中的函數。
getMethod的基本語法如下:
public Method getMethod(String name, Class... parameterTypes) throws NoSuchMethodException, SecurityException
其中,name為指定方法名,parameterTypes為被調用函數的參數類型列表,根據這兩個參數可以唯一定位一個方法。如果找不到指定的方法,會拋出NoSuchMethodException異常。
二、使用步驟
1、獲取方法所屬的Class對象
首先需要獲取要調用的方法的所在類的Class對象。Class對象可以通過類名獲取,也可以通過實例對象獲取。
2、獲取Method對象
有了Class對象,就可以通過getMethod方法獲取指定的Method對象了。
Class clazz = MyClass.class; 
Method method = clazz .getMethod("myMethod");
如果需要獲取帶參數的方法,則需要在getMethod方法中傳遞參數類型數組。
Method method = clazz.getMethod("myMethod", String.class, int.class);
3、通過Method對象調用方法
通過Method對象的invoke方法,可以動態地執行指定方法。invoke方法可以接收兩個參數,第一個參數為要被調用方法的實例對象(如果該方法是靜態的,則為null),第二個參數為要被調用方法的參數列表。
MyClass myObj = new MyClass(); method.invoke(myObj, "hello", 123);
另外,如果要調用靜態方法,則第一個參數可以為null。
method.invoke(null, "hello", 123);
三、示例代碼
import java.lang.reflect.Method;
public class MyClass {
    
    public void myMethod() {
        System.out.println("調用了無參方法");
    }
    
    public void myMethod(String str, int num) {
        System.out.println("調用了帶參數方法,參數為:" + str + ", " + num);
    }
    
    public static void main(String[] args) throws Exception {
        // 獲取Class對象
        Class clazz = MyClass.class;
        
        // 獲取無參方法
        Method method1 = clazz.getMethod("myMethod");
        method1.invoke(new MyClass());
        
        // 獲取帶參數的方法
        Method method2 = clazz.getMethod("myMethod", String.class, int.class);
        method2.invoke(new MyClass(), "hello", 123);
    }
}
四、總結
Java getMethod是一個反射方法,可以在運行時通過字元串動態調用類中的函數。通過三個步驟獲取要調用的方法,再通過Method對象的invoke方法調用方法。這種動態調用方法的能力可以使程序更加靈活,尤其是在一些需要動態調用方法的場合,為程序員提供了很大的便利。
原創文章,作者:RHFF,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/142661.html
 
 微信掃一掃
微信掃一掃  支付寶掃一掃
支付寶掃一掃 