java 之 动态代理学习示例

import java.lang.reflect.Method;


public interface Advice {
	public void beforeMethod(Method method);
	public void afterMethod(Method method);
}
import java.lang.reflect.Method;


public class MyAdvice implements Advice {
	long beginTime = 0;
	public void beforeMethod(Method method) {
		System.out.println("start.........................");
		beginTime = System.currentTimeMillis();
	}
	public void afterMethod(Method method) {
		System.out.println("end...........................");
		long endTime = System.currentTimeMillis();
		System.out.println(method.getName()+" running time of "+(endTime-beginTime));
	}
}

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

import org.omg.CORBA.portable.InvokeHandler;


public class ProxyTest {

	/**
	 * 创建动态代理类
	 * 查看其方法列表信息
	 * class Proxy${
	 * 	InvocationHandler handler;
	 * 	add(Object object) {
	 * 		return handler.invoke(Object proxy,Method method, Object[] args);
	 * 	}
	 * }
	 * hashCode,equals,toString 委托给了handler,invoke调用,return null
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		//拿到代理类字节码
		Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
		//拿到构造方法
		Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
		
		class MyInvocationHandler implements InvocationHandler {

			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				return null;
			}
			
		}
		
		//实例化代理对象
		/*Collection proxy1 = (Collection) constructor.newInstance(new MyInvocationHandler());
		
		//invocationHandler Proxy类里实现的toString() invoke--->return null;
		//此处结果:null. proxy1!=null
		System.out.println(proxy1);
		proxy1.clear();*/
		
		//此处报错,因为invoke放回的是null,相当于void,而size方法是有返回值的
		// java.lang.NullPointerException
		//proxy1.size();
		
		/*Collection proxy2 = (Collection) constructor.newInstance(new InvocationHandler() {

			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				// TODO Auto-generated method stub
				return null;
			}
			
		});*/
		
		/*Collection proxy3 = (Collection) Proxy.newProxyInstance(Collection.class.getClassLoader(), new Class[]{Collection.class},new InvocationHandler() {
			
			ArrayList<String> arrayList = new ArrayList<String>();
			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				long beginTime = System.currentTimeMillis();
				Object retVal = method.invoke(arrayList, args);
				long endTime = System.currentTimeMillis();
				
				System.out.println(method.getName()+" is running of  "+(endTime-beginTime));
				
				return retVal;
			}
		});
		
		proxy3.add("aaa");
		proxy3.add("bbb");
		proxy3.add("ccc");
		System.out.println(proxy3.size());*/
		
		final ArrayList target = new  ArrayList();
		Collection proxy4 = (Collection) getProxy(target, new MyAdvice());
		proxy4.add("aaa");
		System.out.println(proxy4.size());
		System.out.println(proxy4.getClass().getName());
	}

	public static void getMethodList() {
		//代理类字节码
				Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
				System.out.println(clazzProxy1);
				
				System.out.println("------------------------构造方法列表-----------------------------");
				
				//代理类构造方法
				Constructor[] constructors = clazzProxy1.getConstructors();
				for(Constructor constructor:constructors) {
					String name = constructor.getName();
					StringBuilder sBuilder = new StringBuilder(name);
					
					sBuilder.append('(');
					Class[] clazzParams = constructor.getParameterTypes();
					for(Class clazzParam:clazzParams) {
						sBuilder.append(clazzParam.getName()).append(",");
					}
					if(clazzParams!=null&&clazzParams.length!=0) {
						sBuilder.deleteCharAt(sBuilder.length()-1);
					}
					sBuilder.append(')');
					
					//打印各个构造方法
					System.out.println(sBuilder.toString());
				}
				
				
		System.out.println("------------------------方法列表-----------------------------");
				
				//代理类构造方法
				Method[] methods = clazzProxy1.getMethods();
				for(Method method:methods) {
					String name = method.getName();
					StringBuilder sBuilder = new StringBuilder(name);
					
					sBuilder.append('(');
					Class[] clazzParams = method.getParameterTypes();
					for(Class clazzParam:clazzParams) {
						sBuilder.append(clazzParam.getName()).append(",");
					}
					if(clazzParams!=null&&clazzParams.length!=0) {
						sBuilder.deleteCharAt(sBuilder.length()-1);
					}
					sBuilder.append(')');
					
					//打印各个构造方法
					System.out.println(sBuilder.toString());
				}
	}
	
	public static Object getProxy(final Object target, final Advice advice) {
			Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),new InvocationHandler() {
						
						@Override
						public Object invoke(Object proxy, Method method, Object[] args)
								throws Throwable {

							advice.beforeMethod(method);
							Object retVal = method.invoke(target, args);
							advice.afterMethod(method);
							
							return retVal;
						}
					});
			return proxy;
	}
}

advice 把执行逻辑封装到一个类里边,AOP的做法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值