编写可生成代理和插入通告的通用方法


package com.itheima.shipin.daili;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;

public class ProxyTestII {

	public static void main(String[] args) throws Exception {
		Collection proxy3 = (Collection) Proxy.newProxyInstance(
				// 匿名内部类
				Collection.class.getClassLoader(),
				new Class[] { Collection.class }, new InvocationHandler() {

					@Override
					public Object invoke(Object proxy, Method method,
							Object[] args) throws Throwable {
						System.out.println("proxy.newProxyInstance");
						return null;
					}
				});
		proxy3.clear();

	}
}

将以上的代码进行修改将其变成通用方法。

	private static Object getProxy(final Object target,
			final MyInterface myinterface) {
		Object proxy3 = Proxy.newProxyInstance(
		// 匿名内部类
				target.getClass().getClassLoader(), target.getClass()
						.getInterfaces(), new InvocationHandler() {
					public Object invoke(Object proxy, Method method,
							Object[] args) throws Throwable {
						// long begintime = System.currentTimeMillis();
						myinterface.beforMethod(method);
						Object retVal = method.invoke(target, args);
						myinterface.afterMethod(method);
						// System.out.println("proxy.newProxyInstance");
						// long endtime = System.currentTimeMillis();
						// System.out.println(endtime - begintime);
						return retVal;
					}
				});
		return proxy3;
	}

为了调试我们再做个MyInterface结构以及其实现类。

MyInterface.java

package com.itheima.shipin.daili;

import java.lang.reflect.Method;

public interface MyInterface {
	public void beforMethod(Method method);
	public void afterMethod(Method method);
}

MyInterfaceM.java

package com.itheima.shipin.daili;

import java.lang.reflect.Method;

public class MyInterfaceM implements MyInterface {

	@Override
	public void beforMethod(Method method) {
		// TODO Auto-generated method stub
		System.out.println("beginning heima");
	}

	@Override
	public void afterMethod(Method method) {
		// TODO Auto-generated method stub
		System.out.println("end............");
	}

}

再写测试方法。

	public static void main(String[] args) {

		// TODO Auto-generated method stub
		final ArrayList target = new ArrayList();
		Collection proxy = (Collection) getProxy(target, new MyInterfaceM());
		proxy.add("abc");
		proxy.add("abcd");
		proxy.add("abcdf");
		System.out.println(proxy);
	}

运行结果

beginning heima
end............
beginning heima
end............
beginning heima
end............
beginning heima
end............
[abc, abcd, abcdf]





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值