将数组映射到对象

时间:2017-07-12 07:27:50

标签: java arrays

我有一个如下定义的数组:

String [] source = {"26", "Tom", "foo", ...};

Person班级:

public class Person{
   private String age;
   private String name;
   private String print;
   private String ......;//the same type and order and number of source
   public Person() {

   }
   //full construtors
   public Person(String age, String name, String print,String ....) {
       this.age = age;
       this.name = name;
       this.print = print;
       //....
    }

    /* setters & getters */

}

如何将这些值映射到Person实例?

这是我的真实编码

  public static List<BasicalVo> readObject(String path) throws IOException, NoSuchMethodException {
        InputStreamReader fReader = new InputStreamReader(new FileInputStream(path),"gb2312");
        BufferedReader bufferedReader = new BufferedReader(fReader);
        String currentLine;
        String[] temp;
        List<BasicalVo> basicalVoList= new ArrayList<BasicalVo>();
        while ((currentLine = bufferedReader.readLine()) != null) {
            temp = currentLine.split(",");//I get the Array
            for (int i = 0; i < temp.length; i++) {
                //I don't know hot to translate to BasicalVo .
                BasicalVo vo = new BasicalVo();
                basicalVoList.add(vo);
            }
        }
        return basicalVoList;
    }

5 个答案:

答案 0 :(得分:3)

如果source只包含一个个人的数据,那么您可以这样做:

Person p = new Person(source[0], source[1], source[2] ...);

如果数组太短,则会抛出ArrayIndexOutOfBoundsException

答案 1 :(得分:3)

<强>我

如果数组只包含一个Person,则只需创建如下实例:

String[] source = new String[]{"26", "tom", "xx", "....."};
Person p = new Person(source[0], source[1], source[2], source[3],...);

因为您知道构造函数中有多少参数,所以如果数组构建良好,您将不会拥有ArrayIndexOutOfBoundsException

<强> II。

假设你只有3个属性,如果数组是这样的话,你就可以这样做:

String[] source = new String[]{"26", "tom", "xx", "22", "john", "yy"};
ArrayList<Person> list = new ArrayList<>()
for (int i = 0; i < source.length; i += 3) {
     list.add(new Person(source[i], source[i + 1], source[i + 2]));
}

<强> III。

如果您有多个字段,最好这样做:

public Person(String[]source) {
       this.age = source[0];
       this.name = source[1];
       this.print = source[2];
       //....
}

因为它不会为你从循环中读取数据的代码附加费用,并且更容易做你的东西,事实上这并不难,因为在每种情况下如果你喜欢20个字段,您必须分配这20个属性

<强> IV

或使用工厂方法的最后命题:

public static Person createPersoneFromArray(String[] array) {
    Person p = new Person();
    p.setAge(array[0]);
    p.setName(array[1]);
    //...
    return p;
}

在主要方法中:

Person p = Person.createPersoneFromArray(source);

答案 2 :(得分:2)

you can also add another constructor to your BasicalVo class which takes a String[] as input :

public BasicalVo(String [] input) {
   this.age = input[0];
   this.name = input[1];
   this.print = input[2];
   //....
}

which you then can call in your main as follows without additional for loop

....
temp = currentLine.split(",");
BasicalVo vo = new BasicalVo(temp);
basicalVoList.add(vo);
....

答案 3 :(得分:1)

在这种特殊情况下,我认为您最好的选择是使用反射。 Reflection是一组类和接口,允许您在执行时调用不同的方法。例如:

String [] source = { "26", "tom", "xx", ... };
Constructor constructor = Person.class.getConstructors()[0]
constructor.newInstance(source)

考虑到此示例仅起作用,因为您只有一个构造函数,因此Person.class.getConstructors()[0]返回所需的构造函数。你可以尝试使用Person.class.getConstructors(Class<?>...)来获取特定的构造函数,在这种情况下,你需要传递一个带有参数类型的数组。

答案 4 :(得分:1)

您可以使用OpenCSV

CSVReader csvReader = new CSVReader(new FileReader("people.csv"),',');
ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Person.class);
String[] columns = new String[]{"age","name","print"};
mappingStrategy.setColumnMapping(columns);
CsvToBean ctb = new CsvToBean();
List personList = ctb.parse(mappingStrategy, csvReader);