从条目集中获取数据并填充bean

时间:2016-06-23 18:26:09

标签: java

我有一个条目集

例如:

[
    fromyear=2009,toyear=2010,student=Sam,
    fromyear1=2010,toyear1=2011,student1=Don,
    fromyear2=2011,toyear2=2012,student2=Mike
]

现在我有一个班级学生:

class StudentDtls{
    String fromyear,
    String toyear,
    String student
}

我正在迭代上面的条目集,我如何确定

fromyear=2009,toyear=2010,student=Sam come in one object of StudentDtls,
fromyear1=2010,toyear1=2011,student1=Don in second object of StudentDtls and 
fromyear2=2011,toyear2=2012,student2=Mike in third object of StudentDtls  .

后缀可能会持续到10或20。例如,条目集可以有年10,年10和学生10

1 个答案:

答案 0 :(得分:1)

可以使用反射作为下一步:

Map<String, String> map = new HashMap<>();
map.put("fromyear", "2009");
map.put("toyear", "2010");
...

// Map that will contain the StudentDtls instances with the suffix as key
Map<String, StudentDtls> objects = new HashMap<>();
// The pattern used to extract the field name and the suffix if it exists
Pattern pattern = Pattern.compile("([a-z]+)(\\d*)");
for (Map.Entry<String, String> entry : map.entrySet()) {
    // Create the matcher
    Matcher matcher = pattern.matcher(entry.getKey());
    matcher.find();
    // Get the first group corresponding to the field name
    String fieldName = matcher.group(1);
    // Get the second group corresponding to the suffix, "" if it is not provided
    String objectId = matcher.group(2);
    // Get the current object corresponding to the suffix found
    StudentDtls object = objects.get(objectId);
    if (object == null) {
        // It has not been created so far so we create it
        object = new StudentDtls();
        objects.put(objectId, object);
    }
    // Get the field corresponding to the extracted field name
    Field field = StudentDtls.class.getDeclaredField(fieldName);
    // check if the field is accessible
    if (!field.isAccessible()) {
        // Make it accessible to be able to modify its value
        field.setAccessible(true);
    }
    // Set the value of the field for the current object
    field.set(object, entry.getValue());
}
// Print the object created
System.out.println(objects.values());

<强>输出:

[
    StudentDtls{fromyear='2009', toyear='2010', student='Sam'}, 
    StudentDtls{fromyear='2010', toyear='2011', student='Don'}, 
    StudentDtls{fromyear='2011', toyear='2012', student='Mike'}
]