package proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * Created by 10159705 on 16-1-8. */ public class DynamicProxyTest { interface IHello { void sayHello(); } static class Hello implements IHello { @Override public void sayHello() { System.out.println("hello world"); } } static class DynamicProxy implements InvocationHandler { Object originalObj; Object bind(Object originalObj) { this.originalObj = originalObj; return Proxy.newProxyInstance(originalObj.getClass().getClassLoader(), originalObj.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("add by Dynamic proxy:welcome."); return method.invoke(originalObj, args); } } public static void main(String[] args) { System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true"); //这个地方生成的hello实例,这个hello已经不是定义好的hello了 IHello hello = (IHello) new DynamicProxy().bind(new Hello()); hello.sayHello(); } }
时间: 2024-10-21 01:36:40