Java动态代理——JDk&CGLIB

1、JDK:jdk自带;需要接口。

 

HelloWorld.java

public interface HelloWorld {
    void sayHello();
}

 

HelloWorldImpl.java

public class HelloWorldImpl implements HelloWorld{
    @Override
    public void sayHello() {
        System.out.println("HelloWoldImpl-sayHello()方法");
    }
}

 

JDKProxyExample.java

public class JDKProxyExample implements InvocationHandler {
    private Object target = null;

    /**
     * 绑定目标对象和代理对象
     * @param target
     * @return
     */
    public Object bind(Object target) {
        this.target = target;
        // Proxy.newProxyInstance(类加载器, 生成的对象挂靠在哪些接口下, 定义实现方法逻辑的代理类)
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);  // 返回生成的代理对象
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("invoke()运行前");
        Object res = method.invoke(target, args);  // 通过反射实现调度真实对象的方法
        System.out.println("invoke()运行后");
        return res;
    }
}

 

TestJDK.java

public class TestJDK {
    public static void main(String[] args) {
        JDKProxyExample jdk = new JDKProxyExample();
        HelloWorld proxy = (HelloWorld) jdk.bind(new HelloWorldImpl());  // proxy和target对象都在HelloWorld接口下,所以JDK代理方式必须使用接口
        proxy.sayHello();
    }
}

 

输出:

invoke()运行前
HelloWoldImpl-sayHello()方法
invoke()运行后

 

2、CGLIB:第三方;不需要接口。

 

ReflectServiceImpl.java

public class ReflectServiceImpl {
    void sayHello(String name) {
        System.out.println("hello" + name);
    }
}

 

CglibProxyExample.java

public class CglibProxyExample implements MethodInterceptor {
    /**
     * 绑定当前对象和代理对象
     * @param cls
     * @return
     */
    public Object getProxy(Class cls) {
        Enhancer enhancer = new Enhancer();  // cglib enhancer增强类对象
        enhancer.setSuperclass(cls);  // 设置增强类型
        enhancer.setCallback(this);  // 定义代理逻辑对象为当前对象,要求当前对象实现MethodInterceptor方法
        return enhancer.create();  // 返回代理对象
    }


    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("CGLIB代理-运行前");
        Object result = methodProxy.invokeSuper(proxy, args);
        System.out.println("CGLIB代理-运行后");
        return null;
    }
}

 

TestCglib.java

public class TestCglib {
    public static void main(String[] args) {
        CglibProxyExample cpe = new CglibProxyExample();
        ReflectServiceImpl proxy = (ReflectServiceImpl) cpe.getProxy(ReflectServiceImpl.class);
        proxy.sayHello("张三");
    }
}

 

输出:

CGLIB代理-运行前
hello张三
CGLIB代理-运行后

 

posted @ 2023-11-03 15:52  DoubleFishes  阅读(13)  评论(0编辑  收藏  举报