1、
1 public interface MyService { 2 public int add(int a , int b); 3 public int sub(int a , int b); 4 }
2、实现类
1 /** 2 * 实现类 3 */ 4 public class MyServiceImpl implements MyService,YourService { 5 public int add(int a, int b) { 6 return a + b ; 7 } 8 public int sub(int a, int b) { 9 return a - b; 10 } 11 public int multiply(int a, int b) { 12 return a * b ; 13 } 14 public float divide(int a, int b) { 15 return (float)a / b; 16 } 17 public int shiftLeft(int a, int b) { 18 return a << b ; 19 } 20 public int shiftRight(int a, int b) { 21 return a >> b ; 22 } 23 24 public int singleAnd(int a, int b) { 25 return a & b; 26 } 27 28 public boolean doubleAnd(int a, int b) { 29 return false && true; 30 } 31 }
3、
1 public interface YourService { 2 public int multiply(int a , int b); 3 public float divide(int a , int b); 4 public int shiftLeft(int a,int b); 5 public int shiftRight(int a,int b); 6 public int singleAnd(int a,int b); 7 public boolean doubleAnd(int a,int b); 8 9 }
4、
1 public class ProxyMain { 2 public static void main(String[] args) { 3 System.out.println("ProxyMain.hashcode : " + ProxyMain.class.hashCode()); 4 MyServiceImpl s = new MyServiceImpl(); //目标对象 5 System.out.println("s.hashcode : " + s.hashCode()); 6 TimeHandler h = new TimeHandler(s); //处理器对象 7 Class[] clazz = {MyService.class,YourService.class} ;//代理接口数组 8 MyService ms = (MyService) Proxy.newProxyInstance(ProxyMain.class.getClassLoader(), clazz, h); 9 System.out.println(ms.add(2 , 2)); 10 System.out.println(((YourService)ms).multiply(2,2)); 11 System.out.println(ms.sub(2 , 2)); 12 System.out.println(((YourService)ms).shiftLeft(1,2)); 13 System.out.println(((YourService)ms).shiftRight(4,2)); 14 System.out.println(((YourService)ms).singleAnd(4,2)); 15 System.out.println(((YourService)ms).doubleAnd(4,2)); 16 System.out.println(((YourService)ms).divide(4, 4)); 17 System.out.println(((YourService)ms).divide(4, 4)); 18 } 19 20 /** 21 * 时间处理器 22 */ 23 static class TimeHandler implements InvocationHandler{ 24 //目标对象 25 private Object target; 26 27 public TimeHandler(Object target){ 28 this.target = target ; 29 } 30 31 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 32 long start = System.nanoTime() ; 33 //调用目标对象的方法 34 Object retVal = method.invoke(target, args); 35 System.out.println(method.getName() + " : " + (System.nanoTime() - start)); 36 //切记:返回目标对象方法的返回值,否则篡改了业务逻辑。 37 return retVal; 38 } 39 } 40 }