日期:2014-05-20 浏览次数:20659 次
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class RelectTests { public static void main(String[] args) { Hello hello1 = (Hello) Proxy.newProxyInstance(Hello.class.getClassLoader(), new Class[] { Hello.class }, new MyInvocationHandler(new MyHello())); hello1.sayHello("Kitty!"); Hello hello2 = (Hello) Proxy.newProxyInstance(Hello.class.getClassLoader(), new Class[] { Hello.class }, new MyInvocationHandler(new YourHello())); hello2.sayHello("Kitty!"); } } interface Hello{ void sayHello(String name); } class MyHello implements Hello{ @Override public void sayHello(String name) { System.out.println("Hello!, My name is " + name); } } class YourHello implements Hello{ @Override public void sayHello(String name) { System.out.println("Hello!, Your name is " + name); } } class MyInvocationHandler implements InvocationHandler{ private Object delegate; MyInvocationHandler(Object subject){ this.delegate = subject; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; System.out.println("Method start"); result = method.invoke(this.delegate, args); System.out.println("Method end"); return result; } }