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等類型.