通过反射简化模型中多次get set方法
在某些场景里Javabean包含了大量的字段,很多程序员会通过一个一个set get来匹配,这种写法不但繁琐而且代码冗余不好看且维护起来很麻烦,我们可以通过反射来解决:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
/** * 通过反射简化模型中多次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(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 |
import lombok.Data; @Data public class DemoModel { private String height; private String weight; private String age; } |
之后如果DemoModel再扩展字段,不再需要额外地写set、get,只要满足set、get的命名规范约定,直接在paramList里面补充字段名字就可以,后续可扩展性好很多。
暂无评论