利用java.lang.reflect.Proxy 实现代理
结合上一篇文章(自定义annotation 实现注入功能),里面模拟了一个拦截器。
发现在使用的时候都需要去调用SimilarToTheInterceptor.scanAllFieldsAndMethods 方法,
如果说有多个action需要注入,很显然这是种不好的设计。
TestAction action = new TestAction();
SimilarToTheInterceptor.scanAllFieldsAndMethods(action);// 模拟拦截器功能
action.saveDate1();
于是我想到使用java.lang.reflect.Proxy 去实现这个拦截器功能
正对前一篇文章的代码下面几个类需要改变
1.SimilarToTheInterceptor 该名称 ScanHelper 内容保持不变
2.增加一个新类,用来实现 拦截功能
package com.test;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class Handler implements InvocationHandler {private Object obj;public Handler(Object obj) {this.obj = obj;}public static Object newInstance(Object obj) {System.out.println(obj.getClass().getName());return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),new Handler(obj));}public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {Object result = null;if(obj!=null){ScanHelper.scanAllFieldsAndMethods(obj);// 注入result = method.invoke(obj, args);}return result;}}
public interface Action {public void saveDate1();public void saveDate2();}
package com.test;public class Main {public static void main(String[] args) { TestAction a = new TestAction(); Action action = (Action) Handler.newInstance(a); action.saveDate1(); action.saveDate2();}}