Java基础增强-----------代理类的作用
http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训、期待与您交流!
一、概述
程序中的代理:
要为已存在的多个具有相同接口的目标类的各个方法增加一些系统功能,例如,异常处理、日志、计算方法的运行时间、事物管理等等,如何做?
编写一个与目标类具有相同接口的代理类代理类的每个方法调用目标类的相同方法,并在调用方法时加上系统功能代码。
编写一个与目标类具有相同接口的代理类,代理类的每个方法调用目标类的相同方法,并在调用方法时加上系统功能的代码。
如果采用工厂模式和配置文件的方式进行管理,则不需要修改客户端程序,在配置文件中配置是使用目标类、还是代理类,这样以后很容易切换,譬如,想要日志功能时就配置代理类,否则配置目标类,这样,增加系统功能很容易,以后运行一段时间后,又向去掉系统功能也很容易。
交叉业务编程即为面向对象编程(Aspect Orinented program,简称AOP),AOP的目标就是要使交叉业务模块化,可以采用将切面代码移动到原始方法的周围,这与直接在方法中编写切面代码的运行效果一样的。交叉业务是安全、事物、日志等功能要贯彻到好多模块中,所有它们是交叉业务。代理技术正好是解决这种问题,代理是实现AOP功能的核心和关键技术。
要为系统中的各种接口的类增加代理功能,那将要太多的代理类,全部采用静态代理方式,将是一件非常麻烦的事情!写成百上千个代理类,很累人?
JVM可以在运行期动态生成出类的字节码,这种动态生成的类往往被用作代理类,即动态代理类。
JVM生成的动态类必须实现一个或多个接口,所有,JVM生成的动态类只能用作具有相同接口的目标类的代理。
CGLIB库可以动态生成一个类的子类,一个类的子类也用作该类的代理,所有,如果要为一个没有实现接口的类生成动态代理类,那么可以使用CGLIB库。
代理类的各个方法中通常除了要调用目标的相应的方法和对外返回目标的结果外,还可以再代理方法中的如下四个位置加上系统功能代码。
1.在调用目标方法之前
2.在调用目标方法之后
3.在调用目标方法前后
4.在处理目标方法异常的catch块中
二、分析JVM动态生成的类
案例:
创建实现了Collection接口的动态类和查看其名称,分析Proxy.getProxyClass方法的各个参数
编程列出动态类中的所有构造方法和参数签名
编码列出动态类中的所有方法和参数签名
创建动态类的实例对象
用反射获得构造方法
编写一个简单的InvocationHandle类
调用构造方法创建动态类的实例对象,并将编写的InvocationHandle类的实例对象传递进去。
打印创建的对象和调用对象的没有返回值的方法和getClass方法,演示调用其他有返回值的方法报告了异常。
将创建动态类的实例对象的代理改成匿名内部类的形式编写,锻炼大家习惯匿名内部类。
<span style="font-size:12px;">package Proxy;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Collection;
public class ProxyDemo {
/**
* @param args
* 功能:类型代理类的功能
*/
public static void main(String[] args) throws Exception {
Class classProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
Constructor[] constructors = classProxy.getConstructors();
for(Constructor constructor : constructors){
String name = constructor.getName();
StringBuffer sBuffer = new StringBuffer();
sBuffer.append('(');
sBuffer.append(constructor.getName());
Class [] conParamterType = constructor.getParameterTypes();
for(Class paraType : conParamterType ){
sBuffer.append(',');
sBuffer .append(paraType.getName());
}
sBuffer.append(')');
System.out.println(sBuffer.toString());
}
Method [] methods = classProxy.getMethods();
for(Method method : methods){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(method.getName());
stringBuffer.append('(');
Class [] methodTypes = method.getParameterTypes();
for(Class methodType : methodTypes){
stringBuffer.append(methodType.getName());
}
stringBuffer.append(')');
System.out.println(stringBuffer.toString());
}
//InvocationHadler是一个接口,需要编写一个类类实现该接口
//1.通过使用实现的方式类实现InvocationHadler接口
class MyInvocationHadler implements InvocationHandler{
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
}
//获得代理的构造方法,参数为InvocationHadler实现子类,没有无参数构造方法
Constructor conInvocationHadler = classProxy.getConstructor(InvocationHandler.class);
//通过newInstance方法获取一个Collection实例
Collection invocationHadler = (Collection)conInvocationHadler.newInstance(new MyInvocationHadler());
//2.通过匿名内部类实现InvocationHadler接口
Collection invocationHadler2 = (Collection) conInvocationHadler.newInstance(new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
});
//3.通过调用代理类的方式实现
Collection invocationHadler3 = (Collection) Proxy.newProxyInstance(
Collection.class.getClassLoader(),
new Class[] {Collection.class},
new InvocationHandler() {
ArrayList arrayList = new ArrayList();
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return method.invoke(arrayList, args);
}
});
invocationHadler3.add("abc");
invocationHadler3.add("bac");
invocationHadler3.add("cba");
System.out.println(invocationHadler3.size());
}
}
</span>
三、让动态生成的类成为目标类的代理
怎样将目标类传递进去
1.直接在InvocationHadler实现类中创建目标类的实例对象,可以看运行效果和加入日志代码,但没有实际意义。
2.为InvocationHadler实现类注入目标类的实例对象,不能采用匿名内部类的形式了。
3.让匿名的InvocationHandler实现类访问外面方法中的目标类实现对象的final类型的引用变量。
将创建代理的过程改为一种更优雅的方式,eclipse重构出一个getProxy方法绑定接收目标同时返回代理对象,让调用者更懒惰,更方便,调用者甚至不用接触任何代理的API
把系统功能代码模块化,即将切面代码也改为通过参数形式提供,怎样把要执行的系统功能代码以参数形式提供?
1. 把要执行的代码装到一个对象的某个方法里,然后把这个对象作为参数传递,接收者只要调用这个对象的方法,即等于执行了外界提供的代码。
2. 为bind方法增加一个方法。
<span style="font-size:12px;">package Proxy;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Collection;
public class ProxyDemo {
/**
* @param args
* 功能:类型代理类的功能
*/
public static void main(String[] args) throws Exception {
Class classProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
Constructor[] constructors = classProxy.getConstructors();
for(Constructor constructor : constructors){
String name = constructor.getName();
StringBuffer sBuffer = new StringBuffer();
sBuffer.append('(');
sBuffer.append(constructor.getName());
Class [] conParamterType = constructor.getParameterTypes();
for(Class paraType : conParamterType ){
sBuffer.append(',');
sBuffer .append(paraType.getName());
}
sBuffer.append(')');
System.out.println(sBuffer.toString());
}
Method [] methods = classProxy.getMethods();
for(Method method : methods){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(method.getName());
stringBuffer.append('(');
Class [] methodTypes = method.getParameterTypes();
for(Class methodType : methodTypes){
stringBuffer.append(methodType.getName());
}
stringBuffer.append(')');
System.out.println(stringBuffer.toString());
}
//InvocationHadler是一个接口,需要编写一个类类实现该接口
//1.通过使用实现的方式类实现InvocationHadler接口
class MyInvocationHadler implements InvocationHandler{
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
}
//获得代理的构造方法,参数为InvocationHadler实现子类,没有无参数构造方法
Constructor conInvocationHadler = classProxy.getConstructor(InvocationHandler.class);
//通过newInstance方法获取一个Collection实例
Collection invocationHadler = (Collection)conInvocationHadler.newInstance(new MyInvocationHadler());
//2.通过匿名内部类实现InvocationHadler接口
Collection invocationHadler2 = (Collection) conInvocationHadler.newInstance(new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
});
//3.通过调用代理类的方式实现
final ArrayList target = new ArrayList();
Collection invocationHadler3 = (Collection)getProxy(target,new MyAdvice());
invocationHadler3.add("abc");
invocationHadler3.add("bac");
invocationHadler3.add("cba");
System.out.println(invocationHadler3.size());
}
private static Object getProxy(final Object target,final Advice advice) {
Object ProxyMethod = Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(); new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {advice.beforedMethod();Object objVal = method.invoke(target, args);advice.afterMethod();return objVal;
}});
return ProxyMethod;
}
}
package Proxy;
public interface Advice {
//定义一个接口
public void beforedMethod();
public void afterMethod();
}
package Proxy;
public class MyAdvice implements Advice {
long startTime=0;
@Override
public void afterMethod() {
//需要在执行后添加的功能
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
@Override
public void beforedMethod() {
//需要在执行前添加的功能
startTime = System.currentTimeMillis();
}
}
</span>