JDK动态代理主要是通过Proxy对象的
newProxyInstance方法实现。
package java.lang.reflect;
public class Proxy implements java.io.Serializable {
/*
loader:指定类的加载器
interfaces:指定需要实现的接口
h:代理类的调用处理程序,即代理类的实际处理逻辑
*/
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
}
public interface InvocationHandler {
/*
proxy:代理对象
method:要执行的方法
args:要执行的方法的参数
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
}
定义一个接口和它的实现类
public interface UserService {
public void login();
public void register();
}
public class UserServiceImpl implements UserService {
@Override
public void login() {
System.out.println("登录成功");
}
@Override
public void register() {
System.out.println("注册成功");
}
}
需求:模拟给上面的服务类通过JDK动态代理的方式添加日志记录操作
public class TestJDKDynamicProxy {
@Test
public void test(){
UserService userService = getProxy(new UserServiceImpl());
userService.register();
userService.login();
/*
在代理对象中模拟记录日志操作
注册成功
在代理对象中模拟记录日志操作
登录成功
*/
}
public UserService getProxy(UserService userService){
UserService userServiceProxy = (UserService)Proxy.newProxyInstance(
userService.getClass().getClassLoader(),
userService.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("在代理对象中模拟记录日志操作");
Object result = method.invoke(userService, args);
return result;
}
});
return userServiceProxy;
}
}