2013-02-06 36 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 /)为此:) –

相关问题