首先:先来写一个实现类的接口,比如我们就写一个火车启动的过程
public interface Train { public void move() ; public void stop(); }
因为JDK代理必须使用接口来实现,所以接口是必须的,然后我们就来写一个实现类,来实现火车的启动与停止,
public class TrainImp implements Train { public void move() { System.out.println("火车开动了。。。"); } public void stop(){ System.out.println("火车停止了。。。"); } }
接着我们要实现的时通过代理来在Train的方法,,在调用对象的方法前来加入一些东西
public class JDKProxyTest implements InvocationHandler{ private Object object ; public Object createProxy(Object obj){ this.object = obj ; return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("befor"); method.invoke(object, args); System.out.println("after"); return null ; } }
这样一个代理类就写好了,最后是测试方法
public class MainTest { public static void main(String[] args) { JDKProxyTest test = new JDKProxyTest() ; Train obj = (Train) test.createProxy(new TrainImp()); obj.move(); obj.stop(); } }
在move方法前方法后都会有befor或者是after,这就是jdk实现代理的过程