通过反射创建动态代理对象(三)
生活随笔
收集整理的這篇文章主要介紹了
通过反射创建动态代理对象(三)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
一、概述
? ? 傳入目標對象和Advice(要執行的內容)對“通過反射創建動態代理對象(二)”進行改造(AOP框架實現原理),建立更加通用的代理對象。
二、代碼說明
? ? 1、Proxy2IntegrationReform.java
package staticimport.proxy;import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Collection;import staticimport.proxy.advice.Advice; import staticimport.proxy.advice.MyAdvice;/**** * 傳入目標對象和Advice(要執行的內容)(AOP框架實現原理)* * @author Liu**/ public class Proxy2IntegrationReform {public static void main(String[] args) {Collection<String> target = new ArrayList<>();Collection proxy = (Collection) getProxy(target,new MyAdvice());proxy.add("a");proxy.add("b");proxy.add("c");// proxy.clear();System.out.println(proxy.size());}private static Object getProxy(final Object target,final Advice advice) {Object object = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {advice.beforeAdvice(method);Object object = method.invoke(target, args);advice.afterAdvice(method);return object;}});return object;}}? ? 2、接口Advice.java
package staticimport.proxy.advice;import java.lang.reflect.Method;public interface Advice {void beforeAdvice(Method method);void afterAdvice(Method method); }? ? 3、MyAdvice.java
package staticimport.proxy.advice;import java.lang.reflect.Method;public class MyAdvice implements Advice {private long startTime;@Overridepublic void beforeAdvice(Method method) {startTime = System.currentTimeMillis();}@Overridepublic void afterAdvice(Method method) {long endTime = System.currentTimeMillis();System.out.println(method.getName() + " of time consume: " + (endTime - startTime) + " ms");}}?
轉載于:https://my.oschina.net/Howard2016/blog/1617990
總結
以上是生活随笔為你收集整理的通过反射创建动态代理对象(三)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: System.InvalidOperat
- 下一篇: 对高并发流量控制的一点思考推荐