黑马程序员技术交流社区

标题: 黑马程序员--代理 [打印本页]

作者: 敷衍ゝ微笑掩盖    时间: 2014-7-2 15:19
标题: 黑马程序员--代理
本帖最后由 敷衍ゝ微笑掩盖 于 2014-7-2 15:22 编辑

------- <a  target="blank">android培训</a>、<a  target="blank">java培训</a>、期待与您交流! ---------

②  创建动态类及查看其方法列表
Public void abc(){
Class clazzProxy1=Proxy.getProxyClass(Collection.class.getClassLoader(),Collection.class );//获得实现了Collection接口的代理类
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()).get(‘,’);
}
sBuilder.deleteCharAt(sBuilder.length()-1);
sBuilder.append(“)”);
}
Constructor constructor = clazzProxy1.getConstructor(InvocationHander.class);//他的构造方法类型是从上面的代码打印出来知道的。
Collection proxy1= constructor.newInstance(new MyInvocation());//MyInvocationHander是实现了InvocationHander接口的类。也就完成了的动态类的实例化。
③ 一步实现动态类的创建及实例化。
Connection proxy2= (Connection.)Proxy.newProxy().Instance(Collection.class.getClassLoader(),  new class[]{Collection.class}, new InvocationHander{
ArrayList target = new ArrayList();
Public Object invoke(Object proxy, Method method,Object[] args)throws Throwable{
//这可以是代理完成的其它操作
Object retval = method.invoke(target, args);
//这可以是代理完成的其它操作
Return retval;

}
})
Proxy1.add(12);
调用过程:proxy,add,参数12,都传到 invoke(Object proxy, Method method,Object[] args)中去,在Object retval = method.invoke(target, args);调用目标对象的add方法前后可以完成其它的操作,最终把Object retval = method.invoke(target, args);的结果返回,实现了代理的功能。
注意:System.out.println(proxy1.getClass().getName());为什么打印的是Proxy0类而不是ArrayLIst呢,因为Proxy类从Object继承下来的只有hashCode,equals,toString三个方法委托给了Proxy类中的InvocationHander去干,其它没授权,getClass就是未授权之一。
④ 编写可生成代理和插入通告的通用方法(向一个方法中插入位置的代码)
Public Interface Advice{
Void beforeMehod(Method method);
Void afterMehod(Method method);
}
Public classAdvice implement Advice{
Void beforeMehod(Method method){
System.out.println(method.getName());
}
Void afterMehod(Method method){
System.out.println(“顶你个肺”);

}


Private static Object getProxy(final Object target, Advice advice){
Object proxy3=Proxy.newProxy().Instance(target.class.getClassLoader(),
target.getClass().getInterfaces(), new InvocationHander{
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 proxy3;
}

调用:
Final ArrayList target = new ArrayList();
Collection proxy4=getProxy(target, new Advice())

代理原理.png (10.5 KB, 下载次数: 10)

代理原理图

代理原理图

作者: huanglyhf    时间: 2014-7-2 16:57
表示还看不懂{:3_47:}
作者: 暮雨    时间: 2014-7-15 23:21
我就看看,不说话




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2