Java 使用超级CSV自定义bean实例化
Java 使用超级CSV自定义bean实例化,java,csv,supercsv,Java,Csv,Supercsv,CSVBeanReader公开用于读取给定类型的bean 是否有方法传递实际的对象实例而不是对象类型(即自定义bean实例化)?更新: 我刚刚发布了,它支持和同时填充现有bean。耶 我是一个超级CSV开发者。使用超级CSV(和)提供的读卡器无法做到这一点,而且它以前也没有作为功能请求出现过。你可以提交一个,我们会考虑在下一个版本中添加它(我希望这个月能出来)。 对您来说,最快的解决方案是编写您自己的CsvBeanReader来实现这一点——只需将CsvBeanReader的源代码复制到您的源
CSVBeanReader
公开用于读取给定类型的bean
是否有方法传递实际的对象实例而不是对象类型(即自定义bean实例化)?更新: 我刚刚发布了,它支持和同时填充现有bean。耶
我是一个超级CSV开发者。使用超级CSV(和)提供的读卡器无法做到这一点,而且它以前也没有作为功能请求出现过。你可以提交一个,我们会考虑在下一个版本中添加它(我希望这个月能出来)。 对您来说,最快的解决方案是编写您自己的CsvBeanReader来实现这一点——只需将CsvBeanReader的源代码复制到您的源代码中,并根据需要进行修改 我首先将
populateBean()
方法重构为两个方法(重载,因此一个调用另一个)
/**
*实例化bean(如果是接口,则创建代理),并将处理的列映射到
*豆子。
*
*@param-clazz
*要实例化的bean类(如果提供了接口,将创建一个代理),使用默认值
*(无参数)构造函数
*@param nameMapping
*名称映射
*@返回已填充的bean
*@svreflectionexception
*如果在填充bean时出现反射异常
*/
私有T populateBean(最终类clazz,最终字符串[]nameMapping){
//实例化bean或代理
最终T结果bean=实例化的ebean(clazz);
返回populateBean(resultBean,nameMapping);
}
/**
*通过将处理过的列映射到bean的字段来填充bean。
*
*@param resultBean
*要填充的bean
*@param nameMapping
*名称映射
*@返回已填充的bean
*@svreflectionexception
*如果在填充bean时出现反射异常
*/
私有T populateBean(最终T结果Bean,最终字符串[]名称映射){
//将每个列映射到bean上与其关联的字段
for(int i=0;i
然后,您可以编写自己的read()
方法(基于中的方法),以接受bean实例(而不是它们的类),并调用接受实例的populateBean()
我将此作为练习留给您,但如果您有任何问题,请提问:)我已为此创建了一个示例:)
/**
* 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;
}