← Back to list

java动态代理

Published on: | Views: 72
package cn.com.sjfx.corpwx;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 */
public class ProxyTest {
    public static void main(String[] args) {
        HelloClass helloClass = new HelloClass();
        HelloInterface hello = (HelloInterface) Proxy.newProxyInstance(helloClass.getClass().getClassLoader(),
                helloClass.getClass().getInterfaces(), new JdkProxyInvocationHandler(helloClass));
        hello.hello();

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(HelloClass.class);
        enhancer.setCallback(new CglibMethodInterceptor(helloClass));
        HelloClass cglibProxy= (HelloClass) enhancer.create();
        cglibProxy.hello();
    }

    public interface HelloInterface {
        void hello();
    }

    public static class HelloClass implements HelloInterface {
        @Override
        public void hello() {
            System.out.println("hello world");
        }
    }

    public static class JdkProxyInvocationHandler implements InvocationHandler {
        private Object target;

        public JdkProxyInvocationHandler(Object target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("jdk proxy before");
            Object returnValue = method.invoke(target, args);
            System.out.println("jdk proxy after");
            return returnValue;
        }
    }

    public static class CglibMethodInterceptor implements MethodInterceptor{
        private Object target;

        public CglibMethodInterceptor(Object target) {
            this.target = target;
        }
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("cglib proxy before");
            Object returnValue = method.invoke(target, objects);
            System.out.println("cglib proxy after");
            return returnValue;
        }
    }
}