Java教程:CommonsCollections學(xué)習(xí)筆記(四)

字號(hào):

BeanMap這個(gè)Map類(lèi)用于把一個(gè)javaBean轉(zhuǎn)換為Map,在其中存儲(chǔ)了javaBean的各個(gè)屬性的setXXX方法和getXXX方法,屬性的類(lèi)型。
    public class BeanMap extends AbstractMap implements Cloneable
    {
    private transient Object bean;//javaBean對(duì)象
    private transient HashMap readMethods = new HashMap();//getXXX方法集
    private transient HashMap writeMethods = new HashMap();//setXXX方法集
    private transient HashMap types = new HashMap();//成員變量類(lèi)型集
    public static final Object[] NULL_ARGUMENTS = {};//空參數(shù)集,用于通過(guò)reflection調(diào)用getXXX方法
    public static HashMap defaultTransformers = new HashMap();//把基本類(lèi)型映射為transformer類(lèi)型,后者用于將字符串轉(zhuǎn)換為合適的基本型的包裝類(lèi)
    //默認(rèn)transformer
    static
    {
    defaultTransformers.put( Boolean.TYPE, new Transformer()
    {
    public Object transform( Object input )
    {
    return Boolean.valueOf( input.toString() );
    }
    }
    );
    defaultTransformers.put( Character.TYPE, new Transformer()
    {
    public Object transform( Object input )
    {
    return new Character( input.toString().charAt( 0 ) );
    }
    }
    );
    defaultTransformers.put( Byte.TYPE, new Transformer()
    {
    public Object transform( Object input )
    {
    return Byte.valueOf( input.toString() );
    }
    }
    );
    defaultTransformers.put( Short.TYPE, new Transformer()
    {
    public Object transform( Object input )
    {
    return Short.valueOf( input.toString() );
    }
    }
    );
    defaultTransformers.put(
    Integer.TYPE,
    new Transformer() {
    public Object transform( Object input ) {
    return Integer.valueOf( input.toString() );
    }
    }
    );
    defaultTransformers.put( Long.TYPE, new Transformer()
    {
    public Object transform( Object input ) {
    return Long.valueOf( input.toString() );
    }
    }
    );
    defaultTransformers.put( Float.TYPE, new Transformer()
    {
    public Object transform( Object input ) {
    return Float.valueOf( input.toString() );
    }
    }
    );
    defaultTransformers.put( Double.TYPE, new Transformer()
    {
    public Object transform( Object input ) {
    return Double.valueOf( input.toString() );
    }
    }
    );
    }
    public BeanMap(Object bean) {
    this.bean = bean;
    initialise();
    }
    public Object clone() throws CloneNotSupportedException {
    BeanMap newMap = (BeanMap)super.clone();
    if(bean == null) {//若底層bean不存在,則返回一個(gè)復(fù)制的空BeanMap,
    return newMap;
    }
    Object newBean = null;
    Class beanClass = null;
    try {
    beanClass = bean.getClass();//底層bean的Class
    newBean = beanClass.newInstance();//實(shí)例化一個(gè)新的bean
    } catch (Exception e) {
    // unable to instantiate
    throw new CloneNotSupportedException
    ("Unable to instantiate the underlying bean "" +
    beanClass.getName() + "": " + e);
    }
    try {
    newMap.setBean(newBean);
    } catch (Exception exception) {
    throw new CloneNotSupportedException
    ("Unable to set bean in the cloned bean map: " +
    exception);
    }
    try {
    //復(fù)制所有可讀寫(xiě)的屬性
    Iterator readableKeys = readMethods.keySet().iterator();
    while(readableKeys.hasNext()) {
    Object key = readableKeys.next();//屬性名稱(chēng)
    if(getWriteMethod(key) != null) {
    newMap.put(key, get(key));//放入到新BeanMap中
    }
    }
    } catch (Exception exception) {
    throw new CloneNotSupportedException
    ("Unable to copy bean values to cloned bean map: " +
    exception);
    }
    return newMap;
    }
    public void clear() {
    if(bean == null) return;
    Class beanClass = null;
    try {
    beanClass = bean.getClass();
    bean = beanClass.newInstance();//重新實(shí)例化,一切都回到默認(rèn)狀態(tài)
    }
    catch (Exception e) {
    throw new UnsupportedOperationException( "Could not create new instance of class: " + beanClass );
    }
    }  public Object get(Object name) {//獲取指定名稱(chēng)屬性的值
    if ( bean != null ) {
    Method method = getReadMethod( name );
    if ( method != null ) {
    try {
    return method.invoke( bean, NULL_ARGUMENTS );
    }
    catch ( IllegalAccessException e ) {
    logWarn( e );
    }
    catch ( IllegalArgumentException e ) {
    logWarn( e );
    }
    catch ( InvocationTargetException e ) {
    logWarn( e );
    }
    catch ( NullPointerException e ) {
    logWarn( );
    }
    }
    }
    return null;
    }
    public Object put(Object name, Object value) throws IllegalArgumentException, ClassCastException
    {//設(shè)置指定名稱(chēng)的屬性的值
    if ( bean != null ) {
    Object oldValue = get( name );//原來(lái)的值
    Method method = getWriteMethod( name );
    if ( method == null ) {
    throw new IllegalArgumentException( "The bean of type: "+ bean.getClass().getName() + " has no property called: " + name );
    }
    try {
    Object[] arguments = createWriteMethodArguments( method, value );//轉(zhuǎn)換參數(shù)
    method.invoke( bean, arguments );//設(shè)置新值
    Object newValue = get( name );//獲取新設(shè)置的值
    firePropertyChange( name, oldValue, newValue );//fire屬性值改變事件
    }
    catch ( InvocationTargetException e ) {
    logInfo( e );
    throw new IllegalArgumentException( e.getMessage() );
    }
    catch ( IllegalAccessException e ) {
    logInfo( e );
    throw new IllegalArgumentException( e.getMessage() );
    }
    return oldValue;
    }
    return null;
    }
    public Method getReadMethod(String name) {//獲取指定名稱(chēng)屬性的getXXX方法
    return (Method) readMethods.get(name);
    }
    public Method getWriteMethod(String name) {//獲取指定名稱(chēng)屬性的setXXX方法
    return (Method) writeMethods.get(name);
    }
    private void initialise()
    {
    if(getBean() == null) return;
    Class beanClass = getBean().getClass();//bean的Class
    try
    {
    //BeanInfo beanInfo = Introspector.getBeanInfo( bean, null );
    BeanInfo beanInfo = Introspector.getBeanInfo( beanClass );//bean的信息
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    if ( propertyDescriptors != null )
    {
    for ( int i = 0; i < propertyDescriptors.length; i++ )
    {
    PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
    if ( propertyDescriptor != null )
    {
    String name = propertyDescriptor.getName();//屬性名稱(chēng)
    Method readMethod = propertyDescriptor.getReadMethod();//getXXX方法
    Method writeMethod = propertyDescriptor.getWriteMethod();//setXXX方法
    Class aType = propertyDescriptor.getPropertyType();//屬性類(lèi)型
    if ( readMethod != null ) {
    readMethods.put( name, readMethod );//保存到getXXX集合
    }
    if ( writeMethod != null ) {
    writeMethods.put( name, writeMethod );//保存到setXXX集合
    }
    types.put( name, aType );//保存屬性類(lèi)型
    }
    }
    }
    }
    catch ( IntrospectionException e ) {
    logWarn( e );
    }
    }
    protected static class MyMapEntry extends AbstractMapEntry
    {//BeanMap使用的Map entry
    private BeanMap owner;//所屬的Map
    protected MyMapEntry( BeanMap owner, Object key, Object value ) {
    super( key, value );
    this.owner = owner;
    }
    public Object setValue(Object value) {
    Object key = getKey();
    Object oldValue = owner.get( key );
    owner.put( key, value );
    Object newValue = owner.get( key );
    super.setValue( newValue );
    return oldValue;
    }
    }
    protected Object[] createWriteMethodArguments( Method method, Object value ) throws IllegalAccessException, ClassCastException
    {
    try
    {
    if ( value != null )
    {
    Class[] types = method.getParameterTypes();//setXXX方法的參數(shù)類(lèi)型
    if ( types != null && types.length > 0 )
    {
    Class paramType = types[0];
    if ( ! paramType.isAssignableFrom( value.getClass() ) )
    {
    value = convertType( paramType, value );//把新參數(shù)轉(zhuǎn)換為setXXX方法的參數(shù)類(lèi)型
    }
    }
    }
    Object[] answer = { value };
    return answer;
    }
    catch ( InvocationTargetException e ) {
    logInfo( e );
    throw new IllegalArgumentException( e.getMessage() );
    }
    catch ( InstantiationException e ) {
    logInfo( e );
    throw new IllegalArgumentException( e.getMessage() );
    }
    }
    protected Object convertType( Class newType, Object value )
    throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    // try call constructor
    Class[] types = { value.getClass() };
    try {//嘗試用帶一個(gè)參數(shù)的構(gòu)造函數(shù)進(jìn)行轉(zhuǎn)換
    Constructor constructor = newType.getConstructor( types );
    Object[] arguments = { value };
    return constructor.newInstance( arguments );
    }
    catch ( NoSuchMethodException e ) {
    // try using the transformers
    Transformer transformer = getTypeTransformer( newType );//獲取可用的transformer
    if ( transformer != null ) {
    return transformer.transform( value );//轉(zhuǎn)換類(lèi)型
    }
    return value;
    }
    }
    protected Transformer getTypeTransformer( Class aType ) {
    return (Transformer) defaultTransformers.get( aType );
    }
    }