共计 2327 个字符,预计需要花费 6 分钟才能阅读完成。
jdk 静态代理
public interface AddService {Integer add(int a, int b);
}
public class AddServiceImpl implements AddService {
@Override
public Integer add(int a, int b) {return a + b;}
}
public class AddServiceProxy implements AddService{
private AddService addService;
public AddServiceProxy(AddService addService) {this.addService = addService;}
public static void main(String[] args) {AddService addService = new AddServiceImpl();
AddService addServiceProxy = new AddServiceProxy(addService);
addServiceProxy.add(1, 3);
}
@Override
public Integer add(int a, int b) {System.out.println("before");
int result = addService.add(a, b);
System.out.println("result:" + result);
System.out.println("after");
return result;
}
}
jdk 动态代理
jdk 动态代理的业务类必须实现接口
public interface AddService {Integer add(int a, int b);
}
业务类的实现类
public class AddServiceImpl implements AddService {
@Override
public Integer add(int a, int b) {return a + b;}
}
代理类的生成
public class AddServiceHandler implements InvocationHandler {
private AddService addService;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("before");
Object invoke = method.invoke(addService, args);
System.out.println(invoke);
System.out.println("after");
return invoke;
}
public AddServiceHandler(AddService addService) {this.addService = addService;}
public AddService getProxy() {return (AddService) Proxy.newProxyInstance(addService.getClass().getClassLoader(), addService.getClass().getInterfaces(), this);
}
public static void main(String[] args) {AddService service = new AddServiceImpl();
AddServiceHandler addServiceHandler = new AddServiceHandler(service);
AddService proxy = addServiceHandler.getProxy();
proxy.add(1, 2);
}
}
cglib 动态代理
业务类不需要实现接口,但不能业务类需要继承,所以业务类不能是 final 及业务类的相应方法不能是 final
public class AddServiceImpl {public Integer add(int a, int b) {return a + b;}
}
public class AddServiceCglib implements MethodInterceptor {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {System.out.println("before");
Object result = methodProxy.invokeSuper(o, objects);
System.out.println("result:" + result);
System.out.println("after");
return result;
}
public Object getInstance(Class clzz) {Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clzz);
enhancer.setCallback(this);
return enhancer.create();}
public static void main(String[] args) {AddServiceCglib cglib = new AddServiceCglib();
AddServiceImpl addServiceImpl = (AddServiceImpl) cglib.getInstance(AddServiceImpl.class);
addServiceImpl.add(1,7);
}
}
正文完
发表至: java
2019-11-08