Java实现动态代理
- JDK提供的基于接口的动态代理机制,使用InvocationHandler和Proxy实现
- cglib提供的基于继承的动态代理机制,使用Enhancer和MethodInterceptor实现
优缺点
- jdk的动态代理,要求被代理的类必须实现接口
- cglib的动态代理,不要求被代理的类实现接口,但要求被代理的类方法,必须能被重写(final会代理失败)
代码实现
基于JDK实现的动态代理
package utils.dynamic;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKProxy {
static class SelfInvocationHandler implements InvocationHandler {
private Object target;
public SelfInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("JDK dynamic proxy:before...");
Object invoke = method.invoke(target, args);
System.out.println("JDK dynamic proxy:after...");
return invoke;
}
public <T> T getProxy() {
return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
}
public static void main(String[] args) {
User user = new User("zyu", 18);
UserService service = new SelfInvocationHandler(new UserServiceImpl()).getProxy();
service.addUser(user);
}
interface UserService {
void addUser(User user);
}
static class UserServiceImpl implements UserService {
@Override
public void addUser(User user) {
System.out.println("add user:" + user);
}
}
static class User {
private String name;
private Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}
基于cglib实现的动态代理
package utils.dynamic;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CGlibProxy {
static class CGLibMethodInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("cglib dynamic proxy:before...");
Object invoke = methodProxy.invokeSuper(o, objects);
System.out.println("cglib dynamic proxy:after...");
return invoke;
}
}
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserServiceImpl.class);
enhancer.setCallback(new CGLibMethodInterceptor());
UserServiceImpl service = (UserServiceImpl) enhancer.create();
service.addUser(new User("zyu", 18));
}
static class UserServiceImpl{
public void addUser(User user) {
System.out.println("add user:" + user);
}
}
static class User {
private String name;
private Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}