1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy;
interface OrderService { void createOrder(String orderId); }
class OrderServiceImpl implements OrderService { @Override public void createOrder(String orderId) { System.out.println("创建订单: " + orderId); } }
class OrderServiceProxy implements InvocationHandler { private final Object target;
public OrderServiceProxy(Object target) { this.target = target; }
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { long startTime = System.currentTimeMillis(); System.out.println("开始执行: " + method.getName());
Object result = method.invoke(target, args);
long endTime = System.currentTimeMillis(); System.out.println("执行完成: " + method.getName() + ", 耗时: " + (endTime - startTime) + "ms"); return result; } }
public class ExtendedJdkProxyDemo { public static void main(String[] args) { OrderService target = new OrderServiceImpl();
OrderService proxy = (OrderService) Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), new OrderServiceProxy(target) );
proxy.createOrder("12345"); } }
|