Kava Pava Gava Tava Nava Zava Java

everything about Java
随笔 - 15, 文章 - 0, 评论 - 1, 引用 - 0
数据加载中……

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;
    }

}

posted on 2009-12-23 18:10 bing 阅读(344) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: