问题描述
如果我有一个非原始公共成员的类,并且我想从一个CSV文件用OpenCSV填充它们,我该怎么做呢?我注意到OpenCSV有一些与PropertyDescriptors有关的受保护的成员
所以让我们假设我有一个Person类有一个Address成员,我的CSV文件包含detailsd为每个人包括他们的地址..
人{
private String name;
private地址al
public void setAddress(Address a){..}
public void setName(String name){..}
}
Addess {
private String line1;
private String line2;
private String postCode;
。
。
。
}
CSV档案:
NAME | ADDR1 | ADDR2 | PCODE ...
John Smith |有些地方|一些城镇| NW234
感谢,
- 但我遇到了同样的情况,有两种方法来处理它。您可以覆盖CsvToBean.convertValue或CsvToBean.getPropertyEditor。
分类方法可能是覆盖getPropertyEditor并为您的特定对象返回一个自定义PropertyEditor。快速和脏的方式将覆盖在匿名类形式的convertValue,如下:
CsvToBean< MyClass> csvToBean = new CsvToBean< MyClass>(){
@Override
protected Object convertValue(String value,PropertyDescriptor prop)throws InstantiationException,IllegalAccessException {
if .getName()。equals(myWhatever)){
//基于传入值返回一个自定义对象
return new MyWhatever((String)value);
}
return super.convertValue(value,prop);
}
};
这对OpenCSV 2.3的工作很好。祝你好运!
If I have a class with non-primitive public members and I want to populate them from a CSV file with OpenCSV, how can I do this? I notice that OpenCSV has some protected members relating to PropertyDescriptors
So let's say I have a Person class that has an Address member, and my CSV file contains the detailsd for each person including their address..
Person{
private String name;
private Address al
public void setAddress(Address a){..}
public void setName(String name){..}
}
Addess{
private String line1;
private String line2;
private String postCode;
.
.
.
}
CSV file:
NAME | ADDR1 | ADDR2 | PCODE ...
John Smith |Some place | Some town | NW234
Thanks,
- A
I'm sure you've long since moved on, but I've run into the same situation and there are two ways to handle it. You can either override CsvToBean.convertValue or CsvToBean.getPropertyEditor.
The classier way is probably to override getPropertyEditor and return a custom PropertyEditor for your particular object. The quick and dirty way would be to override convertValue in anonymous class form, like this:
CsvToBean<MyClass> csvToBean = new CsvToBean<MyClass>(){
@Override
protected Object convertValue(String value, PropertyDescriptor prop) throws InstantiationException,IllegalAccessException {
if (prop.getName().equals("myWhatever")) {
// return an custom object based on the incoming value
return new MyWhatever((String)value);
}
return super.convertValue(value, prop);
}
};
This is working fine for me with OpenCSV 2.3. Good luck!
这篇关于OpenCSV CSV到JavaBean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!