CSVBeanReader
公开methods来读取给定类型的bean。
有没有办法传递实际的对象实例而不是对象类型(即自定义bean实例化)?
答案 0 :(得分:1)
<强>更新强>
我刚刚发布了Super CSV 2.2.0,它允许CsvBeanReader和CsvDozerBeanReader填充现有的bean。耶!
我是超级CSV开发人员。使用Super CSV(CsvBeanReader和CsvDozerBeanReader)提供的阅读器无法做到这一点,并且之前没有出现过功能请求。您可以提交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()
实例
我会把这作为练习留给你,但如果你有任何问题,请问:)