import java.lang.reflect.Field;
class Person {
public String name;
private int age;
}
public class ReflectionExample {
public static void main(String[] args) throws Exception {
Class<?> clazz = Person.class;
// 获取所有公共字段
Field[] fields = clazz.getFields();
for (Field field : fields) {
System.out.println(field.getName());
}
// 获取私有字段并修改值
Field ageField = clazz.getDeclaredField("age");
ageField.setAccessible(true); // 暴力访问私有字段
Person person = new Person();
ageField.set(person, 25);
System.out.println(ageField.get(person)); // 输出:25
}
}
3.3 获取类的方法
通过 getMethods() 或 getDeclaredMethods() 方法获取类的方法。
java
import java.lang.reflect.Method;
class Calculator {
public int add(int a, int b) {
return a + b;
}
private void secretMethod() {
System.out.println("This is a secret method.");
}
}
public class ReflectionExample {
public static void main(String[] args) throws Exception {
Class<?> clazz = Calculator.class;
// 获取所有公共方法
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
// 调用私有方法
Method secretMethod = clazz.getDeclaredMethod("secretMethod");
secretMethod.setAccessible(true);
Calculator calculator = new Calculator();
secretMethod.invoke(calculator); // 输出:This is a secret method.
}
}
4. 反射的应用场景
4.1 动态代理
动态代理利用反射实现接口的动态实现,常用于 AOP(面向切面编程)和 RPC 框架。
mermaid
graph TD
A[客户端] --> B[代理对象]
B --> C[目标对象]
C --> D[执行方法]
4.2 依赖注入
Spring 等框架通过反射实现依赖注入,自动将 Bean 注入到需要的地方。
mermaid
graph TD
A[配置文件] --> B[反射解析]
B --> C[创建Bean]
C --> D[注入依赖]