动态代理在日常的开发中还是比较重要的,下面来总结一下。
首先,什么是动态代理技术呢?当项目中有几个类,每一个类都需要做一些类似的操作,比方说打印日志,现在需求可能有更改,那么你必须要改变每一个类中的相关的方法,如果使用动态代理的话就会轻松很多,因为你只需要在InvocationHandler的invoke方法中做相关的操作即可。
ex:
规定一个接口:
public interface AtitheticCalculator { int add(int i,int j); int sub(int i,int j); int mul(int i,int j); int div(int i,int j); } 下面是它的实现类: public class AtitheticCalculatorImp implements AtitheticCalculator { public int add(int i, int j) { int result=i+j; return result; } public int sub(int i, int j) { int result=i-j; return result; } public int mul(int i, int j) { int result=i*j; return result; } public int div(int i, int j) { int result=i/j; return result; } } 然后是相关的代理类: public class AtithmeticCalculatorLoggingProxy { private AtitheticCalculator target;//要代理的对象 public AtithmeticCalculatorLoggingProxy(AtitheticCalculator target) { this.target = target; } public AtitheticCalculator getLoggingProxy(){ AtitheticCalculator proxy=null; //代理对象由哪一个类加载器进行加载 ClassLoader loader=target.getClass().getClassLoader(); //代理对象的类型,即其中有哪些方法 Class[] interfaces=new Class[]{AtitheticCalculator.class}; //返回代理对象后的处理 InvocationHandler h=new InvocationHandler() { /** * proxy:正在返回的那个代理对象,一般情况下在invoke方法中不是用该对象(有可能会造成死循环) * method:正在被调用的那个对象 * args:调用方法的时候传入的那个参数 * */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { /*System.out.println("invoke..."); return 0;*/ String methodName=method.getName(); //日志 System.out.println("The method "+methodName+" begin with"+ Arrays.asList(args)); //执行方法 Object result=method.invoke(target,args); //日志 System.out.println("The method"+methodName+"ends with"+result); return result; } }; proxy= (AtitheticCalculator) Proxy.newProxyInstance(loader,interfaces,h); return proxy; } } 在代理类中我们通过反射获取到需要代理的对象,然后可以在 InvocationHandler的invoke()函数中可以进行相关的操作,这里将调用的方法名称以及结果进行了输出最后来看一下主程序:
public class Main { public static void main(String[] args) { AtitheticCalculator target=new AtitheticCalculatorImp(); AtitheticCalculator proxy=new AtithmeticCalculatorLoggingProxy(target).getLoggingProxy(); /*int result=target.add(1,2);*/ int result=proxy.add(1,2); System.out.println("--->"+result); /*result=target.div(4,2);*/ int result1=proxy.div(4,2); System.out.println("--->"+result1); } }输出结果: