CSVBeanReader
公开了 methods用于读取给定类型的 bean。
有没有办法传递实际的对象实例而不是对象类型(即自定义 bean 实例化)?
最佳答案
更新:
我刚刚发布了 Super CSV 2.2.0 , 这使得 CsvBeanReader和 CsvDozerBeanReader都填充现有的 bean。耶!
我是一名 super 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( )
接受一个实例。
我会把这个作为练习留给你,但如果你有任何问题,请尽管问 :)
关于java - 使用 Super CSV 自定义 bean 实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14725198/