1、新增被代理类接口
package com.xiangwen.day5; public interface Person { public void say(String str); }
2、新建被代理类实现类。
package com.xiangwen.day5; public class PersonImpl implements Person{ @Override public void say(String str) { System.out.println(str); } }
3、新增代理类
package com.xiangwen.day5; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class PersonProx implements InvocationHandler { private Person person; public PersonProx(Person person) { this.person = person; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("befre---------------"); Object o=method.invoke(person,args); System.out.println("end-----------------"); return o; } }
4、测试
package com.xiangwen.day5; import org.omg.CORBA.portable.InvokeHandler; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; public class Test { public static void main(String[] args) { Person person=new PersonImpl(); InvocationHandler personProx=new PersonProx(person); Person p= (Person) Proxy.newProxyInstance(personProx.getClass().getClassLoader(),person.getClass().getInterfaces(),personProx); p.say("hello"); } }
5、结果