• Java反射通过getter和setter方法实现类的拷贝


     1     private User copyFieldValues(User userData, User user) {
     2         Field[] fields = user.getClass().getDeclaredFields();
     3         String[] fieldNames = getFieldNames(fields);
     4         for (int i = 0; i < fieldNames.length; i++) {
     5             Object value = getFieldValueByName(fieldNames[i], user);
     6             if (value != null) {
     7                 setFieldValueByName(fieldNames[i], userData, value,fields[i].getType());
     8             }
     9         }
    10         return userData;
    11     }
    1     private String[] getFieldNames(Field[] fields) {
    2         String[] fieldNames = new String[fields.length];
    3         for (int i = 0; i < fields.length; i++) {
    4             fieldNames[i] = fields[i].getName();
    5         }
    6         return fieldNames;
    7     }
     1     private Object getFieldValueByName(String fieldName, Object o) {
     2         Object value = null;
     3         try {
     4             String getter = "get" + initStr(fieldName);
     5             Method method = o.getClass().getMethod(getter);
     6             value = method.invoke(o);
     7         } catch (Exception e) {
     8             e.printStackTrace();
     9         }
    10         return value;
    11     }
    1     private void setFieldValueByName(String fieldName, Object o, Object value, Class<?> type) {
    2         try {
    3             String setter = "set" + initStr(fieldName);
    4             Method method = o.getClass().getMethod(setter, type);
    5             method.invoke(o, value);
    6         } catch (Exception e) {
    7             e.printStackTrace();
    8         }
    9     }
    1     private String initStr(String fieldName) {
    2         return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    3     }
  • 相关阅读:
    shell脚本
    Dockerfile
    【剑灵攻略】003、XXXfragment that is not a fragment错误,fragment认不出来
    【剑灵攻略】002、android工程引用方式
    【剑灵攻略】001、底部菜单栏实现
    ViewPager动画切换
    android raw与assets区别
    android+eclipse+maven环境搭建
    解决在IE8中无法使用原生JSON的问题
    Windows Phone Toast通知
  • 原文地址:https://www.cnblogs.com/tyk766564616/p/8665300.html
Copyright © 2020-2023  润新知