ITestDemo接口:
public interface ITestDemo { void test1(); void test2(); }
ProxyDemo类:
public class ProxyDemo implements InvocationHandler { Object obj ;//被代理的对象 public ProxyDemo(Object obj){ this.obj=obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(method.getName()+"方法开始执行"); Object result =method.invoke(this.obj,args); System.out.println(method.getName()+"方法执行完毕"); return result; } }
Test1类
public class Test1 implements ITestDemo{ @Override public void test1() { System.out.println("1"); } @Override public void test2() { System.out.println("2"); } }
Test2类:
public class Test2 { public static void main(String[] args) { ITestDemo t = new Test1(); /* 注意:如果一个对象想要通过Proxy.newProxyInstance方法代理, 那么这个对象的类一定要有相应的接口 就像本类中的ITestDemo接口和实现类Test1 */ t.test1(); t.test2(); System.out.println("==========================="); InvocationHandler handler = new ProxyDemo(t); /* Proxy.newProxyInstance(ClassLoader,interface,h) 参数1是代理对象的类加载器 参数2是被代理的对象的接口 参数3是代理对象 返回值就是成功被代理后的对象t,返回的是Object类型,需要根据当时的情况去类型转换 */ ITestDemo t1 =(ITestDemo) Proxy.newProxyInstance(handler.getClass().getClassLoader(),t.getClass().getInterfaces(),handler ); t1.test1(); System.out.println("--------------------------------"); t1.test2(); } }
输出结果:
1
2
===========================
test1方法开始执行
1
test1方法执行完毕
--------------------------------
test2方法开始执行
2
test2方法执行完毕