程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Commons Collections學習筆記(四)

Commons Collections學習筆記(四)

編輯:關於JAVA

BeanMap這個Map類用於把一個javaBean轉換為Map,在其中存儲了javaBean的各個屬性的setXXX方法和getXXX方法,屬性的類型。

public class BeanMap extends AbstractMap implements Cloneable
{
   private transient Object bean;//javaBean對象

   private transient HashMap readMethods = new HashMap();//getXXX方法集
   private transient HashMap writeMethods = new HashMap();//setXXX方法集
   private transient HashMap types = new HashMap();//成員變量類型集

   public static final Object[] NULL_ARGUMENTS = {};//空參數集,用於通過reflection調用getXXX方法
   public static HashMap defaultTransformers = new HashMap();//把基本類型映射為transformer類型,後者用於將字符串轉換為合 適的基本型的包裝類

   //默認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不存在,則返回一個復制的空BeanMap,
       return newMap;
     }
     Object newBean = null;
     Class beanClass = null;
     try {
       beanClass = bean.getClass();//底層bean的Class
       newBean = beanClass.newInstance();//實例化一個新的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 {
       //復制所有可讀寫的屬性
       Iterator readableKeys = readMethods.keySet().iterator();
       while(readableKeys.hasNext()) {
         Object key = readableKeys.next();//屬性名稱
         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();//重新實例化,一切都回到默認狀態
     }
     catch (Exception e) {
       throw new UnsupportedOperationException( "Could not create new instance of class: " + beanClass );
     }
   }

   public Object get(Object name) {//獲取指定名稱屬性的值
     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( e );
         }
       }
     }
     return null;
   }

   public Object put(Object name, Object value) throws IllegalArgumentException, ClassCastException
   {//設置指定名稱的屬性的值
     if ( bean != null ) {
       Object oldValue = get( name );//原來的值
       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 );//轉換參數
         method.invoke( bean, arguments );//設置新值
         Object newValue = get( name );//獲取新設置的值
         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) {//獲取指定名稱屬性的getXXX方法
     return (Method) readMethods.get(name);
   }

   public Method getWriteMethod(String name) {//獲取指定名稱屬性的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();//屬性名稱
             Method readMethod = propertyDescriptor.getReadMethod();//getXXX方法
             Method writeMethod = propertyDescriptor.getWriteMethod();//setXXX方法
             Class aType = propertyDescriptor.getPropertyType();//屬性類型
             if ( readMethod != null ) {
               readMethods.put( name, readMethod );//保存到getXXX集合
             }
             if ( writeMethod != null ) {
               writeMethods.put( name, writeMethod );//保存到setXXX集合
             }
             types.put( name, aType );//保存屬性類型
           }
         }
       }
     }
     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方法的參數類型
         if ( types != null && types.length > 0 )
         {
           Class paramType = types[0];
           if ( ! paramType.isAssignableFrom( value.getClass() ) )
           {
             value = convertType( paramType, value );//把新參數轉換為setXXX方法的參數類型
           }
         }
       }
       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 {//嘗試用帶一個參數的構造函數進行轉換
       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 );//轉換類型
       }
       return value;
     }
   }

   protected Transformer getTypeTransformer( Class aType ) {
     return (Transformer) defaultTransformers.get( aType );
   }

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved