這貨只能代理接口- -!
java
public class TimeCaculateProxy implements InvocationHandler { private Class<?> obj; public static Object newInstance(Class<?> obj) { return java.lang.reflect.Proxy.newProxyInstance(obj.getClassLoader(), obj.getInterfaces(), new TimeCaculateProxy(obj)); } private TimeCaculateProxy(Class<?> obj) { // Greet接口的實現:GreetImpl this.obj = obj; } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { Object result; try { // 自定義的處理 System.out.println("--before method " + m.getName()); // 調用GreetImpl中方法 result = m.invoke(obj.newInstance(), args); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw new RuntimeException("unexpected invocation exception: " + e.getMessage()); } finally { System.out.println("--after method " + m.getName()); } return result; } }