一: JDK代理类所在包:java.lang.reflect.Proxy 也叫做接口代理。
二:基本形式:
Proxy.newProxyInstance(loader, interfaces, h);
参数1:Loder
类加载器,动态代理类运行时创建。任何类都需要类加载器将其加载到内存中。
一般情况:当前类.Class.getClassLoder();
目标类实例.getClass().getClassLoder();
参数2:interfaces 代理类需要实现的所有接口;
方法:目标实例.getClass().getInterfaces() ;
参数3:InvocationHandler 处理类 接口,必须进行实现类 一般采用匿名内部类。
InvocationHandler 提供invoke() 代理类的每一个方法执行时 , 都将调用一次invoke。
参数1:Object proxy : 代理对象
参数2:Method method :代理对象当前执行的方法的描述对象。
参数3:Object[] args 方法实际参数。
UserService proxyService =(UserService) Proxy.newProxyInstance( MyBeanFactory.class.getClassLoader(), userService.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //前执行 myAspect.beFore(); // 执行目标方法 Object object = method.invoke(userService, args); //(目标类,参数)目标类必须是final // 后执行 myAspect.afTer(); return object; } }); return proxyService; }