Java实现动态代理的两种方式

Java领域中,常用的动态代理实现方式有两种,一种是利用JDK反射机制生成代理,另外一种是使用CGLIB代理。

JDK代理必须要提供接口,而CGLIB则不需要,可以直接代理类。下面分别举例说明。

1.JDK动态代理:

public interface People {
    public void sayHello();
}
复制代码
public class Chinese implements People {

    @Override
    public void sayHello() {
        System.out.println("Chinese say hello.");
    }
}
复制代码
复制代码
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class PeopleInvocationHandler implements InvocationHandler{
    
    private Object peolple;
    
    Intermediary(Object people){
        this.people = people;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {

Object invoke = method.invoke(people, args);
        System.out.println("-------- end ---------");
        return invoke;
    }
}
复制代码
复制代码
import java.lang.reflect.Proxy;

public class Test {
    public static void main(String[] args) {
        People chinese = new People();
        PeopleInvocationHandler invocationHandler = new PeopleInvocationHandler(chinese);
        People proxy = (People) Proxy.newProxyInstance(chinese.getClass().getClassLoader(), chinese.getClass().getInterfaces(), invocationHandler);
        proxy.sayHello();
    }
}
复制代码

2.CGLIB动态代理

需要引入CGLIB相关Jar包

public class Chinese {
    public void sayHello(){
        System.out.println("Chinese say hello");
    }
}
复制代码
import java.lang.reflect.Method;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class ChinesePoxy implements MethodInterceptor {

    @Override
    public Object intercept(Object object, Method method, Object[] args,MethodProxy methodProxy) throws Throwable {
        Object intercept = methodProxy.invokeSuper(object, args);
     System.out.println("-------- end ---------");
    return intercept; 
  }
}
复制代码
复制代码
import net.sf.cglib.proxy.Enhancer;

public class Test {
    public static void main(String[] args) {
        ChineseProxy chineseProxy = new ChineseProxy();
        
        Enhancer enhancer = new Enhancer();  
        enhancer.setSuperclass(Chinese.class);
        enhancer.setCallback(chineseProxy);
        
        Chinese proxy = (Chinese) enhancer.create();
        proxy.sayHello();
    }
}
复制代码
posted on 2018-07-27 14:01  朝雨忆轻尘  阅读(19366)  评论(0编辑  收藏  举报