background
over the statistical interface of an old project, count the data of the last 21 weeks of 161f7ac22c014c, and the returned result is an array of:
[
{"A字段": "A1值", "B字段": "B1值", "week1": 1, "week2": 1, "week3": 2, ......, "week21": 3 },
{"A字段": "A2值", "B字段": "B2值", "week1": 5, "week2": 3, "week3": 12, ......, "week21": 7 },
......
]
The encapsulated result object is:
public class StatRetClass {
private String A字段;
private String B字段;
private Integer week1;
private Integer week2;
......
private Integer week21;
}
Later, the business was changed to count the data of the last 27 weeks , so the class was changed to:
public class StatRetClass {
private String A字段;
private String B字段;
private Integer week1;
private Integer week2;
......
private Integer week21;
private Integer week22;
private Integer week23;
private Integer week24;
private Integer week25;
private Integer week26;
private Integer week27;
}
And later amended several times, most recently changed 79 weeks, each modification, you must write a lot of
weekX
field, as well as the corresponding get&set
method (you can also use lombok
).
So is there a way to support the adjustment statistical weeks with as little code modification as possible?
plan
weekX
fields are not hardcoded, but added dynamically when the object is created. cglib
used here to generate properties dynamically. number of weeks as the 161f7ac22c021b configuration variable WEEKCOUNT, which is convenient to dynamically modify the value
configuration system.
public static <T extends StatRetClass> T buildCompareModelDto(Class<T> clazz) {
Map<String, Class> propertyMap = Maps.newHashMap();
IntStream.range(0, WEEKCOUNT).forEach(i -> {
propertyMap.put("week" + (i + 1), Integer.class);
});
BeanGenerator generator = new BeanGenerator();
generator.setSuperclass(clazz);
BeanGenerator.addProperties(generator, propertyMap);
return (T) generator.create();
}
The original new StatRetClassSub1()
and new StatRetClassSub2()
were changed to StatRetClass.buildCompareModelDto(StatRetClassSub1.class)
and StatRetClass.buildCompareModelDto(StatRetClassSub2.class)
respectively.
Another: The property name generated by cglib
$cglib_prop_
, but the get&set
does not have a prefix. For example, the generated week1
property name is $cglib_prop_week1
, but the get
method is getWeek1()
.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。