动态代理示例

原创
2014/11/07 14:52
阅读数 127
AI总结
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);
	}
}



展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
1
分享
AI总结
返回顶部
顶部