在運行狀態下,對任意一個類,都能知道其所有屬性和方法;對任意一個對象,都能調用它的任意方法。這種動態獲取資訊並動態調用對象方法的功能稱為 Java 反射機制。
核心功能:
package com.beidou.test;
import java.lang.reflect.Method;
public class Dynamic {
public static void main(String[] args) throws Exception {
// 1. 獲取 Class 物件
Class<?> clazz = Dynamic.class;
// 2. 獲取所有宣告的方法
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.print("方法名:" + method.getName());
// 參數類型
Class<?>[] paramTypes = method.getParameterTypes();
for (int i = 0; i < paramTypes.length; i++) {
System.out.print(" | 參數" + i + ":" + paramTypes[i].getName());
}
// 返回類型
System.out.println(" | 返回類型:" + method.getReturnType());
}
// 3. 實例化對象
Object obj = clazz.newInstance();
// 4. 獲取指定方法並調用
// 假設存在 public String getAge(int age, String name)
Method getAge = clazz.getMethod("getAge", int.class, String.class);
Object[] arguments = new Object[]{23, "abc"};
String result = (String) getAge.invoke(obj, arguments);
System.out.println("調用結果:" + result);
}
public String getAge(int age, String name) {
return name + ": " + age;
}
}
| API | 用途 |
|---|---|
Class.forName("全限定名") | 根據類名載入 Class 物件 |
clazz.newInstance() | 調用無參構造器創建實例 |
clazz.getDeclaredMethods() | 獲取所有宣告方法(含 private) |
clazz.getMethod(name, paramTypes) | 獲取指定 public 方法 |
method.invoke(obj, args) | 調用方法 |
clazz.getDeclaredFields() | 獲取所有宣告欄位 |
field.setAccessible(true) | 暴力反射訪問私有欄位 |
Method/Field 物件。