1 public interface Calculator { 2 int add(int i, int j); 3 int sub(int i, int j); 4 int mul(int i, int j); 5 int div(int i, int j); 6 }
. 1 public class CalculatorImp the implements the Calculator { 2 / * . 3 * win if added in each log output process, then it is very difficult to maintain, and, 4 * also destroys the code structure, doped with excess non-functional Code , so that in this way undesirable. 5 * first dynamic proxies way to solve this problem, and thus lead AOP aspects programming ideas . 6 * * / . 7 @Override . 8 public int the Add ( int I, int J) { . 9 int Result = I + J; 10 return Result; . 11 } 12 is 13 is @Override 14 public int sub(int i, int j) { 15 int result=i-j; 16 return result; 17 } 18 19 @Override 20 public int mul(int i, int j) { 21 int result=i*j; 22 return result; 23 } 24 25 @Override 26 public int div(int i, int j) { 27 int result=i/j; 28 return result; 29 } 30 }
Import java.lang.reflect.InvocationHandler; Import the java.lang.reflect.Method; Import the java.lang.reflect.Proxy; Import java.util.Arrays; public class CalculatorLoggingProxy { // define a constructor Calculator objects received public CalculatorLoggingProxy ( Calculator the Calculator) { the this .target = Calculator; } // definition of a proxy object to Private the Calculator target; public the Calculator getLoggingProxy () { the Calculator proxy = null ; // define a class loader for the service proxy object ClassLoader = ClassLoader target.getClass () getClassLoader ();. // type of proxy objects, the method in which what Class [] = the interfaces new new Class [] {. The Calculator class }; // if the proxy object method calls have , the following code is executed of InvocationHandler H = new new of InvocationHandler () { @Override public Object Invoke (Object Proxy, Method, Method, Object [] args) throws the Throwable { System.out.println ( "Method,:" + method.getName ( ) + "BeginWith:" + Arrays.asList (args)); Object Result = method.invoke(target, args); //Object result = h.invoke(target, args); System.out.println("The Method end with :"+result.toString()); return result; } }; proxy = (Calculator) Proxy.newProxyInstance(classLoader, interfaces, h); return proxy; } }
3 public class Main { 4 public static void main(String[] args) { 5 Calculator calculator=new CalculatorImp(); 6 Calculator loggingProxy = new CalculatorLoggingProxy(calculator).getLoggingProxy(); 7 int result=loggingProxy.add(1,2); 8 result=loggingProxy.div(4,2); 9 10 } 11 }