package com.stone.dp.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * jdk自带的动态代理;必须实现了某个接口;<br> */ public class JdkProxy implements InvocationHandler { private Object obj; public JdkProxy(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before..."); Object invoke = method.invoke(obj, args); System.out.println("after..."); return invoke; } /** * @param args */ public static void main(String[] args) { Car car = new Car(); InvocationHandler h = new JdkProxy(car); Movable m = (Movable) Proxy.newProxyInstance(car.getClass() .getClassLoader(), car.getClass().getInterfaces(), h); m.move(); } } /** * 实现的接口; */ interface Movable { public void move(); } /** * 被代理的类; */ class Car implements Movable { @Override public void move() { System.out.println("car is moving..."); } }