JDK的动态代理jdk动态代理
JDK动态代理
如下创建动态代理对象,与cglib非常的类似
1、写一个代理类生成工厂
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class JDKProxy implements InvocationHandler { private Object target; public JDKProxy(Object target) { this.target = target; } /** * 获取代理对象 */ public <T> T gerProxy(Class clazz){ return (T)Proxy.newProxyInstance(clazz.getClassLoader(),new Class[]{clazz},this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("=====前置通知====="); final Object result = method.invoke(target, args); return result; } }接口和实现类
interface MyInterface { String hello(); } public class MyInterfaceImpl implements MyInterface{ @Override public String hello() { System.out.println("======执行了hello方法======"); return "hello"; } }测试代码
1、获取代理对象
2、根据这个对象返回代理对象
3、调用该代理对象方法,会发现也触发了
运行结果
=====前置通知===== ======执行了hello方法====== Process finished with exit code 0