黑马程序员 java学习笔记——动态代理

---------------------- ASP.Net+Android+IO开发S.Net培训、期待与您交流! ----------------------

代理的概念与模式

生活中的代理

武汉人从武汉的代理商手中买联想电脑和直接跑到北京传智播客旁边来找联想总部买电脑,你觉得最终的主体业务目标有什么区别吗?基本上一样吧,都解决了核心问题,但是,一点区别都没有吗?从代理商那里买真的一点好处都没有吗?

程序中的代理

1、要为已存在的多个具有相同接口的目标类的各个方法增加一些系统功能,例如,异常处理、日志、计算方法的运行时间、事务管理、等等,你准备如何做?
2、编写一个与目标类具有相同接口的代理类,代理类的每个方法调用目标类的相同方法,并在调用方法时加上系统功能的代码。 如果采用工厂模式和配置文件的方式进行管理,则不需要修改客户端程序,在配置文件中配置是使用目标类、还是代理类,这样以后很容易切换,例如,想要日志功能时就配置代理类,否则配置目标类,这样,增加系统功能很容易,以后运行一段时间后,又想去掉系统功能也很容易。

代理架构图


AOP

1、系统中存在交叉业务,一个交叉业务就要切入到系统中的一个方面,如下所示:
     安全    事务  日志
StudentService-----------|--------|------|-----
CourseService -----------|--------|------|-----
MiscService      -----------|--------|------|-----

2、用具体的程序代码描述交叉业务:

method1 method2 method3
{                       {                      {
------------------------------------------------------切面
.... .... ......
------------------------------------------------------切面
}                        }                     }

3、交叉业务的编程问题即为面向方面的编程(Aspect oriented program ,简称AOP),AOP的目标就是要使交叉业务模块化。可以采用将切面代码移动到原始方法的周围,这与直接在方法中编写切面代码的运行效果是一样的,如下所示:

------------------------------------------------------切面
func1 func2 func3
{              {                 {
.... .... ......
}              }                 }
------------------------------------------------------切面

使用代理技术正好可以解决这种问题,代理是实现AOP功能的核心和关键技术。

PS:

安全,事务,日志等功能要贯穿到好多个模块中,所以,它们就是交叉业务。
重要原则:不要把供货商暴露给你的客户。

动态代理技术

1、要为系统中的各种接口的类增加代理功能,那将需要太多的代理类,全部采用静态代理方式,将是一件非常麻烦的事情!写成百上千个代理类,是不是太累!
2、JVM可以在运行期动态生成出类的字节码,这种动态生成的类往往被用作代理类,即动态代理类。JVM生成的动态类必须实现一个或多个接口,所以,JVM生成的动态类只能用作具有相同接口的目标类的代理。
3、CGLIB库可以动态生成一个类的子类,一个类的子类也可以用作该类的代理,所以,如果要为一个没有实现接口的类生成动态代理类,那么可以使用CGLIB库。
4、代理类的各个方法中通常除了要调用目标的相应方法和对外返回目标返回的结果外,还可以在代理方法中的如下四个位置加上系统功能代码:
① 在调用目标方法之前
② 在调用目标方法之后
③ 在调用目标方法前后
④ 在处理目标方法异常的catch块中
示例:
class proxy{
	void sayHello(){
		……….
		try{
			target.sayHello();
		}catch(Exception e){
			………..
		}
			………….
	}
}

创建动态类及查看其方法列表信息

以Collection的代理类为例,示例代码如下
import java.lang.reflect.*;
import java.util.*;
class ProxyTest{
	public static void main(String[] args) throws Exception{
		Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
		System.out.println(clazzProxy.getName());
		Constructor[] constructors = clazzProxy.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());			
		}
		Method[] methods = clazzProxy.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());			
		}
	}
}

创建动态类的实例对象及调用其方法

创建动态类实例对象的三种方法

1、通过构造方法传参数的方式
import java.lang.reflect.*;
import java.util.*;
class ProxyTest{
	public static void main(String[] args) throws Exception{
		Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
		Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class);
		class MyInvocationHander1 implements InvocationHandler{
			//实现InvocationHandler接口中的方法
			public Object invoke(Object proxy, Method method, Object[] args)throws Throwable{
				return null;
			}
		}
		//通过有参构造方法实例化动态代理类
		Collection proxy = (Collection)constructor.newInstance(new MyInvocationHander1());
		System.out.println(proxy);
	}
}

2、在构造方法内传入匿名内部类
import java.lang.reflect.*;
import java.util.*;
class ProxyTest{
	public static void main(String[] args) throws Exception{
		Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
		Constructor constructor=clazzProxy.getConstructor(InvocationHandler.class);
		Collection proxy = (Collection)constructor.newInstance(new InvocationHandler(){
			public Object invoke(Object proxy, Method method, Object[] args)throws Throwable{
				return null;
			}
		});
	}
}

3、调用Proxy的静态方法
import java.lang.reflect.*;
import java.util.*;
class ProxyTest{
	public static void main(String[] args) throws Exception{
		Object proxy3 = Proxy.newProxyInstance
		(Collection.class.getClassLoader(),
		new Class[]{Collection.class},
		new InvocationHandler(){
			public Object invoke(Object proxy, Method method, Object[] args)throws Throwable{
				return null;
			}
		});
	}
}

52_完成InvocationHandler对象的内部功能

示例代码如下:
import java.lang.reflect.*;
import java.util.*;
class ProxyTest{
	public static void main(String[] args) throws Exception{
		Object proxy= Proxy.newProxyInstance
		(Collection.class.getClassLoader(),
		new Class[]{Collection.class},
		new InvocationHandler(){
			ArrayList target = new ArrayList();
			public Object invoke(Object proxy, Method method, Object[] args)throws Throwable{
				long beginTime = System.currentTimeMillis();//开始时间
				Object retVal = method.invoke(target, args);
				long endTime = System.currentTimeMillis();//结束时间
				System.out.println(method.getName() + " running time of " + (endTime - beginTime));
				return retVal;
			}
		});

		proxy.add("aaa");
		proxy.add("bbb");
		proxy.add("ccc");
		sop(proxy.size());
		sop(proxy.getClass().getName());
	}
	private static void sop(Object obj){
		System.out.println(obj);
	}
}

动态类的原理图

程序的改进版
1、接口
import java.lang.reflect.Method;
public interface Advice {
	void beforeMethod(Method method);
	void afterMethod(Method method);
}

2、实现接口的类
import java.lang.reflect.Method;
public class MyAdvice implements Advice {
		long beginTime = 0;
		public void afterMethod(Method method) {
		// TODO Auto-generated method stub
		System.out.println("从传智播客毕业上班啦!");		
		long endTime = System.currentTimeMillis();
		System.out.println(method.getName() + " running time of " + (endTime - beginTime));
		}
	public void beforeMethod(Method method) {
		// TODO Auto-generated method stub
		System.out.println("到传智播客来学习啦!");
		beginTime = System.currentTimeMillis();
	}
}

3、代理类
import java.lang.reflect.*;
import java.util.*;
public class ProxyTest{
	public static void main(String[] args) throws Exception{
		Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
		Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
		class MyInvocationHander1 implements InvocationHandler{
			public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
				return null;
			}
		}
		final ArrayList target = new ArrayList();			
		Collection proxy= (Collection)getProxy(target,new MyAdvice());
		proxy.add("zxx");
		proxy.add("lhm");
		proxy.add("bxd");
		System.out.println(proxy.size());
		System.out.println(proxy.getClass().getName());
	}
	private static Object getProxy(final Object target,final Advice advice) {
		Object proxy= Proxy.newProxyInstance(
				target.getClass().getClassLoader(),
				target.getClass().getInterfaces(),
				new InvocationHandler(){
					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;
	}
}

----------------------  ASP.Net+Android+IO开发S .Net培训 、期待与您交流! ----------------------

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值