反射与接口
2014-06-21 22:14
197 查看
今天看了动态代理的原理
可以猜测动态生成的代理类的结构如下:
上面有行代码method.invoke(arrayList, args)
我想为什么这个method.invoke()可以接受arrayList对象
我开始是这样认为的,认为通过这个proxyClass类得到Class对象,然后再得到的"add"这个方法对象,调用时是只能传入ProxyClass类产生的实例。
但结果不是,这个方法还能接受ArrayList对象的实例。
后面通过如下代码发现:
否则的话必须一一对应。
<span style="white-space:pre"> </span>Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class); Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class); Collection collection2 = (Collection)constructor.newInstance(new InvocationHandler(){ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object object = method.invoke(arrayList, args); return object; } }); collection2.add("aa"); collection2.add("bb"); System.out.println(collection2.toString());
可以猜测动态生成的代理类的结构如下:
<span style="white-space:pre"> </span>public class ProxyClass{ <span style="white-space:pre"> </span>public ProxyClass(InvocationHandle handle){ <span style="white-space:pre"> </span>this.handle = handle; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public void add(Object obj){ <span style="white-space:pre"> </span>handle.invoke(this,this.getClass().getMethod("add“),obj); <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>}
上面有行代码method.invoke(arrayList, args)
我想为什么这个method.invoke()可以接受arrayList对象
我开始是这样认为的,认为通过这个proxyClass类得到Class对象,然后再得到的"add"这个方法对象,调用时是只能传入ProxyClass类产生的实例。
但结果不是,这个方法还能接受ArrayList对象的实例。
后面通过如下代码发现:
public class GenericMethod implements Fu{ public static void main(String[] args) throws Exception { //Class clazz = GenericMethod.class; //由这个GenericMethod类的字节码得到的show方法调用时只能传入GenericMethod对象实例。否则调用会出错 Class clazz = Fu.class;//由这个父类的直字节码得到的show方法调用时只能所有的其子类对象实例,并能成功调用show方法 Method method = clazz.getMethod("show", null); GenericMethod genericMethod = new GenericMethod(); GenericMethod2 genericMethod2 = new GenericMethod2(); method.invoke(genericMethod2, null); } @Override public void show() { System.out.println("GenericMethod"); } } class GenericMethod2 implements Fu{ @Override public void show() { System.out.println("GenericMethod2"); } } interface Fu{ void show(); }
否则的话必须一一对应。
相关文章推荐
- 设计模式实践-反射到所有接口实现类实践工厂方法,页面中有大量计算数据时设计实践
- Effective Java 学习笔记(第53条:接口优先于反射机制)
- .NET反射和接口的混合使用
- C# 反射-不需要接口约束,调用各种方法
- 接口,工厂及反射
- 四、JAVA基础--接口与反射总结
- JAVA常用基础知识点[继承,抽象,接口,静态,枚举,反射,泛型,多线程...]
- Reflection反射,Assembly程序集,Type类型类,AssemblyQualifiedName程序集的限定名,DataTable和IList接口互相转化
- go语言中的接口类型与反射
- Effective Java之接口优先于反射机制(五十三)
- 接口和类 反射的差异性
- 黑马程序员--Java基础加强--12.利用反射操作泛型I【与反射+泛型相关的接口类型综述】【Type】【ParameterizedType】【个人总结】
- 反射相关类Class接口列表分析
- 通过反射中的 TypeBuilder 来动态实现 INotifyPropertyChanged 接口
- Java泛型接口、迭代器与反射机制结合实例,和泛型方法的使用原则
- 接口工厂方法模式解耦与反射机制 Just when I thought that I was out they pull me back
- 2015070303 - EffactiveJava笔记 - 第53条 接口优于反射机制
- java 反射调用带回调接口的函数
- 反射实现接口工厂
- 黑马程序员--Java基础加强--15.利用反射操作泛型IV【通过反射Method解析泛型方法思路】【通过Method对四种Type子接口类型进行解剖】【使用递归对任意复合泛型类型进行彻底解剖】【个人