CopyUtils 講一個對象的所有(或部分)屬性值copy給另外一個對象

public class CopyUtils {get

//部分copy 須要傳屬性名稱
 public static void copyAttribute(Object objSrc,Object objTar,String... attributes){
  for(String attribute:attributes){
   try{
    Field f = objSrc.getClass().getDeclaredField(attribute);
    f.setAccessible(true);
    f.set(objTar,f.get(objSrc));
    f.setAccessible(false);
   } catch (Exception e) {
    //沒有該方法
   }
  }
 }io

//所有copy
 public static void copyAttributeAll(Object objSrc,Object objTar){
  Field[] fields = objSrc.getClass().getDeclaredFields();
  for(Field f:fields){
   try{
    f.setAccessible(true);
    f.set(objTar,f.get(objSrc));
    f.setAccessible(false);
   } catch (Exception e) {
    //沒有該方法
   }
  }
 }
 }class

相關文章
相關標籤/搜索