代码示例,仔细看注释
package com.example.demo_4.llll;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
// 定义目标接口
interface UserService {
void addUser(String username);
}
// 实现目标接口的具体类 (对这个类做增强处理)
class UserServiceImpl implements UserService {
public void addUser(String username) {
System.out.println("添加用户:" + username);
}
}
// 实现InvocationHandler接口,方法增强
class MyInvocationHandler implements InvocationHandler {
//目标对象 (对目标做增强处理)
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
/**
*
* @param proxy 代理实例
* @param method 被调用的方法
* @param args 方法参数
*
* @return
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("动态代理前置操作");
//执行目标对象的方法
Object result = method.invoke(target, args);
System.out.println("动态代理后置操作");
return result;
}
}
public class DynamicProxyExample {
public static void main(String[] args) {
try {
// 创建目标对象
UserService userService = new UserServiceImpl();
// 创建InvocationHandler实例
MyInvocationHandler handler = new MyInvocationHandler(userService);
// 创建动态代理对象
UserService proxy = (UserService) Proxy.newProxyInstance(
userService.getClass().getClassLoader(),
userService.getClass().getInterfaces(),
handler
);
// 通过代理对象调用方法
proxy.addUser("小明");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
运行效果如下
动态代理前置操作
添加用户:小明
动态代理后置操作