什么是动态代理
为什么要用动态代理
实战demo
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
UserServiceProxy userServiceProxy = new UserServiceProxy(new UserServiceImpl());
UserService aaa = userServiceProxy.getInstance();
System.out.println(aaa.getUserName());
System.out.println(aaa.getUserAge());
}
}
interface UserService {
String getUserName();
int getUserAge();
}
class UserServiceImpl implements UserService {
@Override
public String getUserName() {
System.out.println("获取userName");
return "张三";
}
@Override
public int getUserAge() {
return 10;
}
}
class UserServiceProxy implements InvocationHandler {
public UserService userService;
public UserServiceProxy(UserService userService) {
this.userService = userService;
}
public UserService getInstance() {
return (UserService) Proxy.newProxyInstance(
//指定代理对象的类加载器
userService.getClass().getClassLoader(),
//代理对象需要实现的接口,可以同时指定多个接口
userService.getClass().getInterfaces(),
//方法调用的实际处理者,代理对象的方法调用都会转发到这里
this
);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("dynamic proxy start...");
Object result = method.invoke(userService,args);
if (method.getName().equals("getUserName")) {
System.out.println("针对getUserName进行增强处理");
result = "李四";
} else {
System.out.println("其他方法不增强");
}
System.out.println("dynamic proxy end...");
return result;
}
}
控制台输出:
来源:CSDN
作者:雪落南城
链接:https://blog.csdn.net/lbh199466/article/details/104613850