package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyDemo {
public static void main(String[] args) {
ILoadData mysqlHandler = new LoadDataToMysql();
ILoadData handler = LoadDataHandler.newInstance(mysqlHandler, new DataMetrics());
handler.loadData("load data");
}
}
class LoadDataHandler {
public static ILoadData newInstance(ILoadData handler, DataMetrics metrics) {
return (ILoadData) Proxy.newProxyInstance(handler.getClass()
.getClassLoader(), new Class[] { ILoadData.class },
new DataMetricsProxy(handler, metrics));
}
private static class DataMetricsProxy implements InvocationHandler {
private final ILoadData handler;
private final DataMetrics metrics;
private DataMetricsProxy(ILoadData handler, DataMetrics metrics) {
this.handler = handler;
this.metrics = metrics;
}
@Override
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable {
Object result;
try {
long start = now();
result = m.invoke(handler, args);
int processTime = (int) (now() - start);
metrics.incMethodTime(m.getName(), processTime);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: "
+ e.getMessage());
}
return result;
}
}
private static long now() {
return System.nanoTime();
}
}
interface ILoadData {
public void loadData(String data);
}
class LoadDataToMysql implements ILoadData {
@Override
public void loadData(String data) {
System.out.println("load data to mysql");
}
}
class DataMetrics {
public void incMethodTime(String name, long time) {
System.out.println(name + "," + time);
}
}