需求:需要一个能接收属性名,然后操作其属性值的工具类。
public class Utils {
//list的操作
public static List encryptList(List<?> list, Class<?> t, String... pro) throws Exception {
Map<?,?> map = EDPUtils.methods(t,pro);
Method[] getMethods =(Method[]) map.get("get");
Method[] setMethods =(Method[]) map.get("set");
//举例默认为String类型
for (int i=0;i<list.size();i++){
for (int j=0;j<getMethods.length;j++){
String value = getMethods[j].invoke(list.get(i))+"";
if (value != null){
setMethods[j].invoke(list.get(i), value+"1");
}
}
}
return list;
}
//操作单个对象
public static Object encryptObject(Object obj, Class<?> t, String... pro) throws Exception {
Map<?,?> map = EDPUtils.methods(t,pro);
Method[] getMethods =(Method[]) map.get("get");
Method[] setMethods =(Method[]) map.get("set");
for (int j=0;j<getMethods.length;j++){
String value = getMethods[j].invoke(obj)+"";
if (value != null){
setMethods[j].invoke(obj, value="1");
}
}
return obj;
}
//获取get/set方法
public static Map<String,Method[]> methods(Class<?> t, String[] pro) throws Exception{
Map<String,Method[]> map = new HashMap<>();
Field[] fields = t.getDeclaredFields(); //获取所有属性
String proName = Arrays.toString(pro);
List<String> names = new ArrayList<>();
for (Field field:fields){
if (proName.contains(field.getName())) {
names.add(field.getName().substring(0,1).toUpperCase()+field.getName().substring(1));
}
}
Method[] getMethods = new Method[names.size()];
Method[] setMethods = new Method[names.size()];
for (int i=0;i<names.size();i++){
getMethods[i] = t.getMethod("get"+names.get(i));
setMethods[i] = t.getMethod("set"+names.get(i),String.class);
}
map.put("get",getMethods);
map.put("set",setMethods);
return map;
}
}