首页 > 代码库 > java的动态代理

java的动态代理

JDK的动态代理public interface Subject {    Object request();    void hello();}public class RealSubject implements Subject{    public RealSubject(){};    public Object request() {        System.out.println("realsubject");        return 1;    }    public void hello() {        System.out.println("hello");    }}public class ProxySubject implements InvocationHandler {    private Object obj;    public ProxySubject(Object obj) {        this.obj = obj;    }    public Object invoke(Object proxy, Method method, Object[] args)            throws Throwable {        System.out.println("增强前");        //Object m = method.invoke(obj, args);         method.invoke(obj, args);        System.out.println("增强后");        //return m;         return null;    }}public class Test {    public static void main(String[] args) {        ProxySubject proxy = new ProxySubject(new RealSubject());        Subject sub = (Subject) Proxy.newProxyInstance(                RealSubject.class.getClassLoader(),                RealSubject.class.getInterfaces(), proxy);        sub.request();        sub.hello();    }}cglib的动态代理public class HelloWorld {    public void sayHelloWorld() {        System.out.println("HelloWorld!");    }    public int  say() {        System.out.println(11111111);        return 1;    }}public class CglibProxy implements MethodInterceptor {    private Object obj;    public Object createProxy(Object target) {        this.obj = target;        Enhancer enhancer = new Enhancer();        enhancer.setSuperclass(this.obj.getClass());        enhancer.setCallback(this);        enhancer.setClassLoader(target.getClass().getClassLoader());        return enhancer.create();    }    public Object intercept(Object proxy, Method method, Object[] params,            MethodProxy methodProxy) throws Throwable {        System.out.println("增强前");        Object result = methodProxy.invokeSuper(proxy, params);        System.out.println("增强后");        return null;    }}public class Test {    public static void main(String[] args) {        HelloWorld hello = new HelloWorld();        CglibProxy cglibProxy = new CglibProxy();        HelloWorld hw=(HelloWorld) cglibProxy.createProxy(hello);        hw.sayHelloWorld();        hw.say();    }}

 

java的动态代理