【发布时间】:2013-01-21 10:08:38
【问题描述】:
CSVBeanReader 公开 methods 以读取给定类型的 bean。
有没有办法传递一个实际的对象实例而不是对象类型(即自定义 bean 实例化)?
【问题讨论】:
CSVBeanReader 公开 methods 以读取给定类型的 bean。
有没有办法传递一个实际的对象实例而不是对象类型(即自定义 bean 实例化)?
【问题讨论】:
更新:
我刚刚发布了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()。
我会把这个作为练习留给你,但如果你有任何问题,尽管问:)
【讨论】: