其中towTuple是元组```
这个主要思想就是,传进来一个对象数组,和这个数据中元素的类型信息,然后用这个类型信息去处理数组中每一个对象的值,具体这里是处理了把所有返回值为bigDecimal的值,保留3位小数。
你也可以做一些别的事情。
//私有方法,主要是解析javaBean的class中的get和set方法,并配成对。
private static <T> Map<String, TwoTuple<Method, Method>> findMethodMap(Class<T> clazz) {
Map<String, TwoTuple<Method, Method>> methodMap = new HashMap<String, TwoTuple<Method, Method>>();
Method[] methods = clazz.getMethods();
if (methods != null && methods.length > 0) {
for (Method method : methods) {
if (method.getReturnType().equals(BigDecimal.class)) {
String methodName = method.getName();
if (methodName.contains("get")) {
String middleName = methodName.replaceFirst("get", "");
TwoTuple<Method, Method> twoTuple = new TwoTuple<Method, Method>();
twoTuple.setFirst(method);
methodMap.put(middleName, twoTuple);
}
}
}
for (Method method : methods) {
String methodName = method.getName();
if (!methodName.contains("get")) {
if (methodName.contains("set")) {
String middleName = methodName.replaceFirst("set", "");
TwoTuple<Method, Method> methodTwoTuple = methodMap.get(middleName);
if (methodTwoTuple != null) {
methodTwoTuple.setSecond(method);
continue;
}
methodMap.remove(middleName);
}
}
}
}
return methodMap;
}
//主工具方法
public static <T> void handleBeanListBigDecimalScale(List<T> list, Class<T> clazz) {
try {
if (list != null && list.size() > 0 && clazz != null) {
Map<String, TwoTuple<Method, Method>> methodMap = findMethodMap(clazz);
Iterator<T> it = list.iterator();
while (it.hasNext()) {
T item = it.next();
for (TwoTuple<Method, Method> methodTwoTuple : methodMap.values()) {
Method getMethod = methodTwoTuple.getFirst();
BigDecimal value = (BigDecimal)getMethod.invoke(item);
if (value != null) {
Method setMethod = methodTwoTuple.getSecond();
setMethod.invoke(item, value.setScale(MathConstants.SYSTEM_SCALE, MathConstants.SYSTEM_ROUND_WAY));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new AppException("deal bean`s bigdecimal scale error!");
}
}