简体   繁体   English

将数组映射到对象

[英]Map array to object

I have an array defined as follows: 我有一个数组定义如下:

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

And a Person class: 和一个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 */

}

How can I map these values to a Person instance? 如何将这些值映射到Person实例?

this is my real coding 这是我真正的编码

  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;
    }

If the source just contains one person's data then you can do this: 如果source只包含一个人的数据,那么您可以这样做:

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

If the array is too short an ArrayIndexOutOfBoundsException will be thrown. 如果数组太短,将抛出ArrayIndexOutOfBoundsException

I. 一世。

If the array contains only one Person you only need to create the instance like this : 如果数组只包含一个Person ,则只需要创建如下的实例:

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

Because you'll know how many parameters there is in the constructor and so you won't have an ArrayIndexOutOfBoundsException if the array is well-build 因为您将知道构造函数中有多少参数,所以如果数组构建良好,您将不会有ArrayIndexOutOfBoundsException


II. II。

Assuming you have only 3 attributes, you'll be able to do like this if the array is like this : 假设你只有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. III。

If you have multiple fields, you would better do like this : 如果您有多个字段,最好这样做:

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

Because it wouldn't not surcharge the code you have in your loop which read from the data, and make it easier to do your stuff, and in fact this is not hard, because in every case if you have like 20 fields, you'll have to assignate these 20 attributs 因为它不会使您在循环中从数据中读取的代码附加费用,并使您更容易完成您的工作,事实上这并不难,因为在每种情况下,如果您有20个字段,那么'我必须分配这20个属性


IV. IV。

Or last proposition with a factory method : 或者使用工厂方法的最后一个命题:

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

And in the main method : 并在主要方法:

Person p = Person.createPersoneFromArray(source);

you can also add another constructor to your BasicalVo class which takes a String[] as input : 你还可以在BasicalVo类中添加另一个构造函数,它将String []作为输入:

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 然后你可以在你的main中调用如下,而无需额外的for循环

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

In this specific case I think that your best option is to use reflection. 在这个特定的情况下,我认为你最好的选择是使用反射。 Reflection are a set of classes and interfaces that allow you to call different methods at execution time. Reflection是一组类和接口,允许您在执行时调用不同的方法。 For instance: 例如:

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

Take into account that this example only works because you have only one constructor, and so Person.class.getConstructors()[0] returns the constructor you want. 请注意,此示例仅起作用,因为您只有一个构造函数,因此Person.class.getConstructors()[0]返回所需的构造函数。 YOu can try to get the specific constructor with Person.class.getConstructors(Class<?>...) , in that case you would need to pass as a parameter an array with the type of the arguments. 你可以尝试使用Person.class.getConstructors(Class<?>...)来获取特定的构造函数,在这种情况下,您需要将参数类型的数组作为参数传递。

You can use OpenCSV 您可以使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM