反射与动态代理
Java反射与动态代理详解:JDK Proxy、CGLib。
1. 反射
Class<?> clazz = Class.forName("com.example.User");
Method method = clazz.getMethod("setName", String.class);
Object instance = clazz.getDeclaredConstructor().newInstance();
method.invoke(instance, "Alice");
2. JDK 动态代理
interface UserService {
String getName(int id);
}
UserService proxy = (UserService) Proxy.newProxyInstance(
UserService.class.getClassLoader(),
new Class[]{UserService.class},
(obj, method, args) -> {
System.out.println("Before: " + method.getName());
Object result = method.invoke(target, args);
System.out.println("After: " + method.getName());
return result;
}
);
限制:只能代理接口。
3. CGLib 动态代理
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserServiceImpl.class);
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
System.out.println("Before");
Object result = proxy.invokeSuper(obj, args);
System.out.println("After");
return result;
});
UserServiceImpl proxy = (UserServiceImpl) enhancer.create();
优势:可以代理类(通过生成子类)。
4. 对比
| 特性 | JDK Proxy | CGLib |
|---|---|---|
| 代理目标 | 接口 | 类 |
| 性能 | 较快 | 较慢(生成子类) |
| 依赖 | JDK 内置 | 第三方库 |
| final 方法 | 不适用 | 无法代理 |