package com.wh.po; public interface IComputer { void add(int a,int b); void sub(int a,int b); void mul(int a,int b); void div(int a,int b); }
package com.wh.po; public class Computer implements IComputer{ @Override public void add(int a, int b) { System.out.println(a+b); } @Override public void sub(int a, int b) { // TODO Auto-generated method stub } @Override public void mul(int a, int b) { // TODO Auto-generated method stub } @Override public void div(int a, int b) { // TODO Auto-generated method stub } }
package com.wh.po; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ComputerProxy{ private IComputer computer; public ComputerProxy(){} public ComputerProxy(IComputer computer) { this.computer = computer; } public IComputer getComputer(){ //加载类 ClassLoader classLoader=computer.getClass().getClassLoader(); //代理哪些接口 Class[] interfaces=new Class[]{IComputer.class}; //监听 InvocationHandler handler=new InvocationHandler(){ @Override public Object invoke(Object arg0, Method method, Object[] args) throws Throwable { Object result=null; System.out.println("计算开始!"); result=method.invoke(computer,args); System.out.println("计算结束!"); return result; } }; return (IComputer)Proxy.newProxyInstance(classLoader, interfaces,handler); } }
package com.wh.po; public class Test { public static void main(String[] args) { IComputer c = new ComputerProxy(new Computer()).getComputer(); c.add(10, 5); } }