package com.sean.zzzjvm; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * * @Author Sean * @Date 2017/8/20 21:43. * @Version */ public class DynamicProxyTest { //定义一个接口 interface IHello{ void sayHello(); } //实现该接口的类 static class Hello implements IHello{ @Override public void sayHello() { System.out.println("hello world"); } } //建立一个动态代理类,实现InvocationHandler接口 static class DynamicProxy implements InvocationHandler{ Object originalObj; //建立一个代理的方法,在new DynamicProxy().bind(new Hello());执行 Object bind (Object originalObj){ this.originalObj = originalObj; //返回一个代理对象 return Proxy.newProxyInstance(originalObj.getClass().getClassLoader(), originalObj.getClass().getInterfaces(),this); } //默认重写的方法,在 hello.sayHello()执行 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("welcome"); return method.invoke(originalObj,args); } } public static void main(String[] args){ // IHello hello = new Hello(); //调用动态代理的方法 IHello hello = (IHello) new DynamicProxy().bind(new Hello()); hello.sayHello(); } }