/**
* 通过反射简化模型中多次get set方法
*
*/
public class ReflectionTest {
public Map<String, String> adapteModel(String[] paramList, DemoModel model) throws NoSuchMethodException,
SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Map<String, String> map = new HashMap<>();
for (int i = 0; i < paramList.length; i++) {
String methodName = "get" + paramList[i];
Class<? extends DemoModel> clazz = model.getClass();
Method method = clazz.getDeclaredMethod(methodName);
map.put(paramList[i], (String) method.invoke(model));
}
return map;
}
public static void main(String[] args) {
DemoModel model = new DemoModel();
model.setAge("55");
model.setHeight("1.78");
ReflectionTest reflectionTest = new ReflectionTest();
// 只要满足命名规范约定的,增加paramList就能获取需要的字段
String[] paramList = { "Height", "Age" };
try {
System.out.println(reflectionTest.adapteModel(paramList, model));
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
}