JDK动态代理:
(必须继承接口原因:生成的代理需要继承java.lang.reflect.Proxy
类并实现被代理类实现的接口,由于java是单继承的所以只能代理接口)
1.针对接口实现代理,原理是实现被代理类实现的接口;
2.不能对没有实现接口的类进行代理;
3.基于反射,实现相同接口
public interface TestInterface {
void print();
}
public class Test implements TestInterface{
@Override
public void print(){
System.out.println("jdk proxy");
}
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
Object proxy = Proxy.newProxyInstance(test.getClass().getClassLoader(), test.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("方法执行前");
Object res = method.invoke(test, args);
System.out.println("方法执行后");
return res;
}
});
TestInterface p = (TestInterface)proxy;
p.print();
}
}
CGLib代理:
1.针对类进行代理,原理是生成被代理类的子类,并覆盖其方法;
2.不能对被final修饰的类进行代理,因为不能继承final修饰的类;
3.基于asm,修改字节码生成子类
先添加cglib
的包到项目中
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class Test {
public void print(){
System.out.println("jdk proxy");
}
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(test.getClass());
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("方法执行前");
Object res = method.invoke(test, args);
System.out.println("方法执行后");
return res;
}
});
Object proxy = enhancer.create();
Test p = (Test)proxy;
p.print();
}
}
网友评论