首页 > 其他 > 详细

InvocationHandler 动态代理

时间:2015-10-16 19:13:45      阅读:291      评论:0      收藏:0      [点我收藏+]

这货只能代理接口- -! 

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;
	}
}


InvocationHandler 动态代理

原文:http://my.oschina.net/u/272065/blog/518090

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!