要用代理类实现调用的类方法
class Test{
public void sayHello{
system.out.println("hello World!");
}
}
首先代理类是 必须要实现接口
public interface ISayHello { public void sayHello(String name); }
public class SayHelloImpl implements ISayHello{ public void sayHello(String name) { System.out.println("Hello World!"+name); } }
其次定义完了接口和实现类之后就可以定义自己的调用处理类(动态代理中最重要的就是 Proxy 代理实例 和 InvocationHandler )
public class MyInvocationHandler implements InvocationHandler{ private Object implObject ; public MyInvocationHandler (Object implObject){ this.implObject=implObject; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { doBefore(); method.invoke(implObject, args); doAfter(); return null; } private void doBefore(){ System.out.println("执行前添加打印时间:"+System.currentTimeMillis()); } private void doAfter(){ System.out.println("执行后添加打印时间:"+System.currentTimeMillis()); } }
最后就是写测试类了:
public static void main(String[] args) {
ISayHello sayhello = new SayHelloImpl();
ISayHello proxy = (ISayHello) Proxy.newProxyInstance(SayHelloImpl.class.getClassLoader(), SayHelloImpl.class.getInterfaces(), new MyInvocationHandler(sayhello));
proxy.sayHello("gmm");
}
执行结果:
执行前添加打印时间:1520320424505
Hello World!gmm
执行后添加打印时间:1520320424506