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 }