黑马程序员_代理

-------  android培训 java培训 、期待与您交流! ----------

proxy(代理)   AOP 面向方面的编程

概念
    代理模式是常用的Java 设计模式,它的特征是代理类与委托类有同样的接口,代理类主要负责为委托类预处理消息、过滤消息、把消息转发给委托类,以及事后处理消息等。代理类与委托类之间通常会存在关联关系,一个代理类的对象与一个委托类的对象关联,代理类的对象本身并不真正实现服务,而是通过调用委托类的对象的相关方法,来提供特定的服务。

 

代理就是实现AOP功能的核心与关键技术

 

动态代理类:JVM可以再运行期动态生成类的字节码,这种动态生成的类往往被用于代理类,即动态代理

 

JVM生成的动态代理类必须实现一个或多个接口,所以JVM生成的类只能用于具有相同接口的目标类的代理

 

实现动态代理常用的两个静态方法

ProxyClass(Loader,interface.class);

getProxyClass()

    参数loader 指定动态代理类的类加载器,参数interfaces 指定动态代理类需要实现的所有接口

 

newProxyInstance(Loader,interface.class,InvocationHandler);

    参数loader 指定动态代理类的类加载器,参数interfaces 指定动态代理类需要实现的所有接口,参数handler 指定与动态代理类关联的 InvocationHandler 对象

 

由Proxy类的静态方法创建的动态代理类具有以下特点:
   动态代理类是public、final和非抽象类型的;
   动态代理类继承了java.lang.reflect.Proxy类;
   动态代理类的名字以“$Proxy”开头;
   动态代理类实现getProxyClass()和newProxyInstance()方法中参数interfaces指定的所有接口

定义接口:

package cn.hmm.Proxy;

import java.lang.reflect.Method;

public interface Advice {
	void beforeMethod(Method method);
	void afterMehod(Method method);
	
}

接口实现:

package cn.hmm.Proxy;

import java.lang.reflect.Method;

public class MyAdvice implements Advice {

	long beginTime = 0;
	long endTime = 0;
	public void beforeMethod(Method method) {
		// TODO 自动生成的方法存根
		System.out.println("到黑马来学习了.");
		beginTime = System.currentTimeMillis();
	}


	public void afterMehod(Method method) {
		// TODO 自动生成的方法存根
		System.out.println("从黑马毕业了.");
		 endTime = System.currentTimeMillis();
		System.out.println(method.getName()+" running:"+(endTime-beginTime));
	}


}

代理测试:

package cn.hmm.Proxy;

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

public class ProxyDemo {

	public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		// TODO 自动生成的方法存根
		Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
		System.out.println(clazzProxy1.getName());
		
		Constructor[] constructors = clazzProxy1.getConstructors();
		System.out.println("--------------begin constructors list------------");
		
		//列举构造方法
		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(',');
			}
			sBuilder.deleteCharAt(sBuilder.length()-1);
			if(clazzParams != null && clazzParams.length !=0)
				sBuilder.append(')');
			System.out.println(sBuilder);
			//System.out.println(constructor.getName());
		}

			
		//列举方法
			Method[] methods = clazzProxy1.getMethods();
			System.out.println("--------------begin Mehods list------------");
			
			for(Method method:methods){
				String name1 = method.getName();
				StringBuilder sBuilder1 = new StringBuilder(name1);
				sBuilder1.append('(');
				Class[] clazzParams1 = method.getParameterTypes();
				for(Class clazzParam : clazzParams1){
					sBuilder1.append(clazzParam.getName()).append(',');
				}
				
				if(clazzParams1 != null && clazzParams1.length !=0)
					sBuilder1.deleteCharAt(sBuilder1.length()-1);
				sBuilder1.append(')');
				System.out.println(sBuilder1);
			
		}
			
			System.out.println("--------------begin Create instance object------------");
			Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
		/*	class MyInvocationHandler1 implements InvocationHandler{

				@Override
				public Object invoke(Object proxy, Method method, Object[] args)
						throws Throwable {
					// TODO 自动生成的方法存根
					return null;
				}
				
			}*/
			//Collection proxy1 = (Collection)constructor.newInstance(new MyInvocationHandler1());
			Collection proxy1 = (Collection)constructor.newInstance(new InvocationHandler(){

				@Override
				public Object invoke(Object proxy, Method method, Object[] args)
						throws Throwable {
					// TODO 自动生成的方法存根
					return null;
				}
				
			});
			System.out.println(proxy1);
			
			/*Collection proxy3 = (Collection)Proxy.newProxyInstance(
					Collection.class.getClassLoader(),
					new Class[]{Collection.class},
					new InvocationHandler() {
						
						ArrayList target = new ArrayList();
						@Override
						//哪个调用了代理,代理的方法,方法的参数
						public Object invoke(Object proxy, Method method, Object[] args)
								throws Throwable {
							// TODO 自动生成的方法存根
							System.out.println(proxy.getClass().getName());
							long beginTime = System.currentTimeMillis();
							Object retVal = method.invoke(target, args);
							long endTime = System.currentTimeMillis();
							System.out.println(method.getName()+" running:"+(endTime-beginTime));
							return retVal;
						}
					}
				);
			proxy3.add("zxx");
			proxy3.add("lhm");
			proxy3.add("bxd");
			System.out.println(proxy3.size());*/
			
			final ArrayList target = new ArrayList();
			Collection proxy3 = (Collection)getProxy(target,new MyAdvice());
			proxy3.add("zxx");
			proxy3.add("lhm");
			proxy3.add("bxd");
			System.out.println(proxy3.size());
	}

	private static Object getProxy(final Object target,final Advice advice) {
		//Collection proxy3 = (Collection)Proxy.newProxyInstance(
				//Collection.class.getClassLoader(),
				//new Class[]{Collection.class},
		Object proxy3 = (Object)Proxy.newProxyInstance(		
		target.getClass().getClassLoader(),
				target.getClass().getInterfaces(),
				new InvocationHandler() {
					
					
					@Override
					//哪个调用了代理,代理的方法,方法的参数
					public Object invoke(Object proxy, Method method, Object[] args)
							throws Throwable {
						// TODO 自动生成的方法存根
						/*System.out.println(proxy.getClass().getName());
						long beginTime = System.currentTimeMillis();
						Object retVal = method.invoke(target, args);
						long endTime = System.currentTimeMillis();
						System.out.println(method.getName()+" running:"+(endTime-beginTime));
						return retVal;*/
						System.out.println(proxy.getClass().getName());
						
						advice.beforeMethod(method);
						Object retVal = method.invoke(target, args);
						advice.afterMehod(method);
						
						return retVal;
					}
				}
				);
			return proxy3;
	}

}

------- Windows Phone 7手机开发.Net培训、期待与您交流! -------

详细请查看:www.itheima.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值