Exploring Vaadin (5) 閱讀 com.vaadin.data.util.BeanItem 源代碼
package com.vaadin.data.util;
// 用到了 java.beans 的一些工具,可以學習一下。
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
/** 正如源文件注釋所說,這個 Item 是為了任何普通的 pojo / java bean 準備的。
*/
public class BeanItem extends PropertysetItem {
/** 就是那個 bean */
private final Object bean;
/** 這個初始化方法用 bean 的所有的 property 來生成 Item。property 是用名字來識別的。
* 這個版本僅僅支持 introspectable bean properties(就是說 java introspection 可以發現的,
* 是嗎?),只支持 getter/setter,單獨的 is / are 方法不支持。
*
* 看 getPropertyDescriptors 怎樣得到 property 吧。
*/
public BeanItem(Object bean) {
this(bean, getPropertyDescriptors(bean.getClass()));
}
/** 這個方法用已經準備好的 propertyDescriptors 來初始化。這個可不是公開的初始化方法,內部使用的。
*/
BeanItem(Object bean,
LinkedHashMap<String, PropertyDescriptor> propertyDescriptors) {
// 總之,調用 addItemProperty。看那里吧。
}
/** 用一系列指定的 property 名字來初始化,更靈活一些。 */
public BeanItem(Object bean, Collection<?> propertyIds) {
// 總之還是調用 getPropertyDescriptors 得到一系列的 PropertyDescriptor,然后按照給出的 id 順次 addItemProperty(name, p)
}
// 另一個版本
public BeanItem(Object bean, String[] propertyIds) {
this(bean, Arrays.asList(propertyIds));
}
/** 這個是檢查 bean 得到一系列 property descriptor 的地方 */
static LinkedHashMap<String, PropertyDescriptor> getPropertyDescriptors(
final Class<?> beanClass) {
// 以下利用了 java 提供的方法。注意,這里不是全部代碼,只是我感興趣的地方
try {
final BeanInfo info = Introspector.getBeanInfo(beanClass);
final PropertyDescriptor[] pds = info.getPropertyDescriptors();
// 把全部不是 Object 的get方法加入到 map 中
for (int i = 0; i < pds.length; i++) {
final Method getMethod = pds[i].getReadMethod();
if ((getMethod != null)
&& getMethod.getDeclaringClass() != Object.class) {
pdMap.put(pds[i].getName(), pds[i]);
}
}
} catch (final java.beans.IntrospectionException ignored) {
}
return pdMap;
}
/** 還用說嗎? */
public Object getBean() {
return bean;
}
}