1.首先是一个公共接口
1 public interface Speak{ 2 public void sayHello(); 3 }
2.以及一个该接口的子类
1 public class MySpeak implements Speak{ 2 public void sayHello(){ 3 System.out.println("HelloWorld!"); 4 } 5 }
3.下面我们可以创建对该接口子类对象具体操作的InvocationHandler子类了
1: public class SpeakHandler implements InvocationHandler { 2: //需要操作的目标对象 3: private Object obj; 4: 5: public SpeakHandler(Object obj) { 6: super(); 7: this.obj = obj; 8: } 9: 10: /* @see java.lang.reflect.InvocationHandler#invoke 11: * (java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) 12: */ 13: @Override 14: public Object invoke(Object proxy, Method method, Object[] args) 15: throws Throwable { 16: //执行目标方法前的代码 17: before(); 18: 19: //利用反射执行目标对象的对应方法 20: Object retVal = method.invoke(obj, args); 21: 22: //执行目标方法后的代码 23: after(); 24: 25: return retVal; 26: } 27: 28: private void before(){ 29: System.out.println("before"); 30: } 31: 32: private void after(){ 33: System.out.println("after"); 34: } 35: }
4.最后测试一下,这样就可以利用Proxy类获取我们的代理类对象了,它没有名字哦
1: public class ProxyTest { 2: 3: /** 4: * @param args 5: */ 6: public static void main(String[] args) { 7: 8: //生成目标对象 9: MySpeak ms = new MySpeak(); 10: 11: //生成Handler对象 12: SpeakHandler speakHandler = new SpeakHandler(ms); 13: 14: //构造代理类,获取对象 15: Speak speak = (Speak)Proxy.newProxyInstance( 16: Speak.class.getClassLoader(), 17: new Class[]{Speak.class}, 18: speakHandler); 19: 20: //执行代理类实现的接口方法 21: speak.sayHello(); 22: } 23: }
5.最后两部也可以合成一步来写,是这个样子的.
1 public class ProxyTest { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 8 //生成目标对象 9 MySpeak ms = new MySpeak(); 10 11 //构造代理类,获取对象 12 Speak speak = (Speak)Proxy.newProxyInstance( 13 Speak.class.getClassLoader(), 14 new Class[]{Speak.class}, 15 new InvocationHandler(){ 16 17 //需要操作的目标对象 18 private Object obj; 19 20 public SpeakHandler(Object obj) { 21 super(); 22 this.obj = obj; 23 } 24 25 public Object invoke(Object proxy, Method method, Object[] args) 26 throws Throwable { 27 //执行目标方法前的代码 28 before(); 29 30 //利用反射执行目标对象的对应方法 31 Object retVal = method.invoke(obj, args); 32 33 //执行目标方法后的代码 34 after(); 35 36 return retVal; 37 } 38 39 private void before(){ 40 System.out.println("before"); 41 } 42 43 private void after(){ 44 System.out.println("after"); 45 } 46 }); 47 //执行代理类实现的接口方法 48 speak.sayHello(); 49 } 50 }