通過反射將一個物件的值賦給另一個物件中對應的屬性 不需要用set、get
阿新 • • 發佈:2019-01-09
/** * @method test * @author BinCain * @return void * @date 2017/11/5 0005 2:19 * @Description: 將srcObj物件欄位的值拷貝到destObj欄位(前提:兩個物件中的欄位名相同時) * 其實就是通過反射將值先存在map中,在遍歷set進目標物件 */ public static void copyFieldToBean(Object srcObj,Object destObj){ Map<String, Object> srcMap = new HashMap<String, Object>(); Field[] srcFields = srcObj.getClass().getDeclaredFields(); for (Field srcField : srcFields) { try { srcField.setAccessible(true); srcMap.put(srcField.getName(), srcField.get(srcObj)); //獲取屬性值 } catch (Exception e) { e.printStackTrace(); } } Field[] destFields = destObj.getClass().getDeclaredFields(); for (Field destField : destFields) { destField.setAccessible(true); if (srcMap.get(destField.getName()) == null) { continue; } try { destField.set(destObj, srcMap.get(destField.getName())); //給屬性賦值 } catch (Exception e) { e.printStackTrace(); } } }
/**
* @author BinCain
* @version V1.0
* @Description: 第一個測試實體類:作為資源實體類
* @date 2017/11/5 0005 2:08
*/
public class FirstPerson {
private String name;
private int age;
//GETTER && SETTER
/** * @author BinCain * @version V1.0 * @Description: 第二個測試實體類:作為目標實體類 * @date 2017/11/5 0005 2:08 */ public class SecondPerson { private String name; private int age; //GETTER && SETTER
public static void main(String[] args) { FirstPerson firstPerson = new FirstPerson(); SecondPerson secondPerson = new SecondPerson(); firstPerson.setAge(18); firstPerson.setName("LiLi"); copyFieldToBean(firstPerson,secondPerson); Field[] fds = secondPerson.getClass().getDeclaredFields(); for (Field fd : fds) { try { fd.setAccessible(true); System.out.println(fd.getName() + "=" + fd.get(secondPerson)); } catch (Exception e) { e.printStackTrace(); } } }
測試記結果如下:(符合預想)
name=LiLi
age=18
Process finished with exit code 0