反射和动态代理实现上下文切入AOP效果
生活随笔
收集整理的這篇文章主要介紹了
反射和动态代理实现上下文切入AOP效果
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java的反射框架提供了動態代理機制,允許在運行期對目標類生成代理,避免重復開發,實現上下文切入的功能。
代碼是最好的交流語言:
Subject接口
RealSubject實現接口
SubjectHandler實現上下文切入,非顯式動態代理功能
interface Subject {public String request(int[] array);public void anotherRequest(); } public class RealSubject implements Subject {@Overridepublic String request(int[] array) {System.out.println("real do something");for(int at:array) {System.out.print(at+" ");}System.out.println();return "";}@Overridepublic void anotherRequest() {System.out.println("anotherRequest");}public void ownMethod() {System.out.println("ownMethod");}}?
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method;public class SubjectHandler implements InvocationHandler{private Subject subject;public SubjectHandler(Subject _subject) {subject = _subject;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {System.out.println("預處理...權限校驗");Object obj = method.invoke(subject, args);System.out.println("后處理...數據校驗");return obj;}}?
下面是如何調用:
public static void main(String[] args) {Subject subject = new RealSubject();InvocationHandler handler = new SubjectHandler(subject);ClassLoader cl = subject.getClass().getClassLoader();/** Returns an instance of a proxy class for the specified interfaces * that dispatches method invocations to the specified invocation handler.* 傳入的是Subject接口的所有方法*/Subject proxy = (Subject) Proxy.newProxyInstance(cl, subject.getClass().getInterfaces(), handler);//調用其中一個方法,有傳入參數和返回參數int[] array = {1,2,3};String a =proxy.request(array);System.out.println(a);//調用另外一個方法 proxy.anotherRequest();/*** 用了代理和反射實現了上下文切入!* 不需要顯式創建代理類即實現代理功能,而且不僅僅代理Subject,* 在handler中讀取持久化數據即可實現動態代理,而且invoke上下處理,還可以實現動態切入的效果,這也是AOP編程概念*/}輸入如下
預處理...權限校驗 real do something 1 2 3 后處理...數據校驗預處理...權限校驗 anotherRequest 后處理...數據校驗?
轉載于:https://www.cnblogs.com/yanghuahui/p/3632636.html
總結
以上是生活随笔為你收集整理的反射和动态代理实现上下文切入AOP效果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 20140328项目日志
- 下一篇: 如何让FPGA中的SPI与其他模块互动起