共計 867 個字符,預計需要花費 3 分鐘才能閱讀完成。
Java 反射調用類的方法可以通過以下步驟實現:
- 獲取需要調用方法的類的 Class 對象,可以使用
Class.forName()
方法傳入類的全限定名獲取,也可以通過對象的getClass()
方法獲取。 - 通過 Class 對象的
getMethod()
或getDeclaredMethod()
方法獲取要調用的方法對象。getMethod()
方法可以獲取公有方法,而getDeclaredMethod()
方法可以獲取所有方法,包括私有方法。 - 設置方法的可訪問性,如果要調用的方法是私有方法,可以使用
setAccessible(true)
方法將其設置為可訪問。 - 調用方法對象的
invoke()
方法,并傳入要調用方法的對象以及方法的參數。
以下是一個示例代碼,演示了如何使用反射調用類的方法:
import java.lang.reflect.Method;
public class ReflectMethodExample {public static void main(String[] args) throws Exception {
// 獲取類的 Class 對象
Class clazz = MyClass.class;
// 獲取要調用的方法對象
Method method = clazz.getDeclaredMethod("myMethod", String.class, int.class);
// 設置方法的可訪問性
method.setAccessible(true);
// 創(chuàng)建類的實例
MyClass myObject = new MyClass();
// 調用方法
method.invoke(myObject, "Hello", 123);
}
}
class MyClass {private void myMethod(String str, int num) {System.out.println("String:" + str);
System.out.println("Number:" + num);
}
}
以上代碼中,我們通過反射調用了私有方法myMethod()
,并傳入了字符串和整數參數。
丸趣 TV 網 – 提供最優(yōu)質的資源集合!
正文完