将java列表转换为对象

时间:2016-06-14 17:26:45

标签: java list

我必须将包含一些字符串的列表转换为java对象,这是列表:

[099882, 11, 6, 0, 25]

此列表的每个位置代表java类中的一个字段,这是类:

public class Chunks extends BaseModel {
    private static final long serialVersionUID = 1494042139468968199L;

    private String field1;
    private String field2;
    private String field3;
    private String field4;
    private String field5;

    public Chunks(String field1, String field2, String field3, String field4, String field5) {
         this.field1 = field1;
         this.field2 = field2;
         this.field3 = field3;
         this.field4 = field4;
         this.field5 = field5;
    }   

}

我就像那样填写清单:

private static void splitFile(Path path){
    int[] fileSplits = {6,2,1,1,2};
    int total = 0;

    List<String> stringList = new ArrayList<String>();
    for (int i = 0 ; i < fileSplits.length ; i++) {
        stringList.add(path.toString().substring(total, total+=fileSplits[i]));
    }

    // Have to transform the list just right here !!!
    //      and then..
    //          dbInsert(convertedObject);
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

也许您可以在构造函数的签名中使用数组,而不是列出所有字段:

sudo gem install cocoapods

您甚至可以使用数组来保存Chunk的字段:

public class Chunk{
    private static final long serialVersionUID = 1494042139468968199L;

    private String field1;
    private String field2;
    private String field3;
    private String field4;
    private String field5;

    public Chunk(String[] fields) {
         this.field1 = fields[0];
         this.field2 = fields[1];
         this.field3 = fields[2];
         this.field4 = fields[3];
         this.field5 = fields[4];
    } 
}

无论哪种方式,另一段代码只需要向Chunk的构造函数提供字符串数组:         int [] fileSplits = {6,2,1,1,2};         int total = 0;

public Chunk(String[] fields) {
        this.fields = fields;
    } 

您当然应该添加一些验证,以确保不会在Chunk的构造函数中抛出ArrayOutOfBoundException。

    String[] stringList = new String[fileSplits.length];
    for (int i = 0 ; i < fileSplits.length ; i++) {
       stringList = path.toString().substring(total, total+=fileSplits[i]);
    }

    Chunk chunk = new Chunk(stringList);