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(); } }