您的位置:首页 > 编程语言 > Java开发

Introspector内省和反射的区别. 什么是Bean,对应的jdk概念有哪些,

2014-11-21 18:06 288 查看
Introspector 是一个专门处理bean的工具类.用来获取Bean体系里的 propertiesDescriptor,methodDescriptor.

要理解这个,就要理解下面几个议题.

*bean是啥?

普通的class 可能有 computerAges(){ }等方法.
Bean是 一个field ,有 get 或者set. 除了这些别无其他.
bean是class的一种
例如 public class People {
String
name;
public
String getName(){
}

public
void setName(String name){
}

}
*Bean在jdk里对应的的概念
BeanInfo , 他包含了Bean所有的descriptor(描述符)
.
BeanDescriptor
PropertiesDescriptor MethodDescriptor

* 一个类的属性field 和 propertiesDescriptor(描述)有什么区别.

propertiesDescriptor,它来至于 对Method的解析.
如果是严格的Bean.例如上面的People. field一个叫做name, propertiesDescriptor 只有一个,刚好也是name, 来自set和get的解析, 解析出来都是
name.,所有两个merge为一个.


详细逻辑见Introspector中代码.见附件

* 反射的method和bean概念体系里的methodDescriptor的区别
2:1的对应关系. People里有set和get两个方法,反射得到两个Method,但这两个method会组合成一个MethodDescriptor.

* Introspector内省 和 反射的区别和关系?
Introspector 是一个专门处理bean的工具类.用来获取Bean体系里的 propertiesDescriptor,methodDescriptor.

利用反射获取Method信息,是反射的上层.
性能优化: 只进行一次反射解析. 通过WeakReference静态类级别缓存Method, 在jvm不够时会被回收.
// Static Caches to speed up introspection.
private static Map declaredMethodCache = Collections.synchronizedMap(new WeakHashMap());

附件1:
解析method得到properties,并且合并同名的properties.
把 method根据 解析出的properties放入的map中,将 setMethod和 getMethod合并成一个 methodDescriptor

见 Introspector.java的

/**
* Populates the property descriptor table by merging the
* lists of Property descriptors.
*/
private void processPropertyDescriptors() {



...

// Complete simple properties set
pd = mergePropertyDescriptor(gpd, spd); //merge get方法解析出的gpd和set方法解析出的spd
. 一个PropertyDescriptor里面有两个属性,一个是setMethodName,一个是getMethodName.




....

properties.put(pd.getName(), pd);



}

/**
* Adds the property descriptor to the indexedproperty descriptor only if the
* types are the same.
*
* The most specific property descriptor will take precedence.
*/
private PropertyDescriptor mergePropertyDescriptor(IndexedPropertyDescriptor ipd,
PropertyDescriptor pd) {

}

PropertyDescriptor里的 private Reference<Class> propertyTypeRef; 里的值决定了type,
距离, int string等类型.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: