2013-02-06 39 views

回答

1

更新:

我剛剛發佈Super CSV 2.2.0,使CsvBeanReaderCsvDozerBeanReader既填充現有的bean。好極了!


我是一名超級CSV開發人員。使用Super CSV隨附的閱讀器(CsvBeanReaderCsvDozerBeanReader)無法做到這一點,並且它之前沒有作爲功能請求提供。你可以提交一個feature request,我們會考慮在下一個版本中添加它(我希望在本月出來)。

最快的解決方案就是編寫自己的CsvBeanReader,只需將CsvBeanReader的源文件複製到您的文件中並根據需要進行修改即可。

我首先將populateBean()方法重構爲2個方法(超載,所以一個調用另一個)。

/** 
    * Instantiates the bean (or creates a proxy if it's an interface), and maps the processed columns to the fields of 
    * the bean. 
    * 
    * @param clazz 
    *   the bean class to instantiate (a proxy will be created if an interface is supplied), using the default 
    *   (no argument) constructor 
    * @param nameMapping 
    *   the name mappings 
    * @return the populated bean 
    * @throws SuperCsvReflectionException 
    *    if there was a reflection exception while populating the bean 
    */ 
    private <T> T populateBean(final Class<T> clazz, final String[] nameMapping) { 

    // instantiate the bean or proxy 
    final T resultBean = instantiateBean(clazz); 

    return populateBean(resultBean, nameMapping); 
    } 

    /** 
    * Populates the bean by mapping the processed columns to the fields of the bean. 
    * 
    * @param resultBean 
    *   the bean to populate 
    * @param nameMapping 
    *   the name mappings 
    * @return the populated bean 
    * @throws SuperCsvReflectionException 
    *    if there was a reflection exception while populating the bean 
    */ 
    private <T> T populateBean(final T resultBean, final String[] nameMapping) { 

    // map each column to its associated field on the bean 
    for(int i = 0; i < nameMapping.length; i++) { 

     final Object fieldValue = processedColumns.get(i); 

     // don't call a set-method in the bean if there is no name mapping for the column or no result to store 
     if(nameMapping[i] == null || fieldValue == null) { 
     continue; 
     } 

     // invoke the setter on the bean 
     Method setMethod = cache.getSetMethod(resultBean, nameMapping[i], fieldValue.getClass()); 
     invokeSetter(resultBean, setMethod, fieldValue); 

    } 

    return resultBean; 
    } 

然後,您可以編寫自己的read()方法(基於CsvBeanReader的那些),接受bean實例(而不是他們的階級),並調用接受一個實例populateBean()

我將離開這個作爲練習你,但如果你有任何問題,只是問:)

+0

我創建了一個[功能要求(http://sourceforge.net/p/supercsv/功能請求/ 28 /)爲此:) –

相關問題