在 Java 中,反射(Reflection)可以在运行时动态获取类的信息并调用其方法。下面从基本步骤、常见示例、注意事项三个方面说明。
Class 对象Method 对象Method.invoke()public class UserService {
public void sayHello(String name) {
System.out.println("Hello, " + name);
}
private int add(int a, int b) {
return a + b;
}
}
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws Exception {
// 1. 获取 Class 对象
Class<?> clazz = Class.forName("UserService");
// 2. 创建实例
Object obj = clazz.getDeclaredConstructor().newInstance();
// 3. 获取 Method
Method method = clazz.getMethod("sayHello", String.class);
// 4. 调用方法
method.invoke(obj, "Tom");
}
}
✅ 输出:
Hello, Tom
Method method = clazz.getDeclaredMethod("add", int.class, int.class);
method.setAccessible(true); // 关键:允许访问私有方法
Object result = method.invoke(obj, 3, 5);
System.out.println(result); // 8
public class MathUtil {
public static int square(int x) {
return x * x;
}
}
Method method = MathUtil.class.getMethod("square", int.class);
Object result = method.invoke(null, 4); // 静态方法第一个参数为 null
| 方法 | 说明 |
|---|---|
Class.forName() |
根据类名获取 Class |
clazz.getMethod() |
获取 public 方法 |
clazz.getDeclaredMethod() |
可获取私有方法 |
method.invoke() |
执行方法 |
setAccessible(true) |
绕过访问控制 |
NoSuchMethodExceptionIllegalAccessExceptionInvocationTargetException如果你指的是 其他语言(如 C# / Python) 或 特定场景(如调用构造方法、泛型方法),可以继续问我。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。