将一个对象的属性copy到另外一个对象里去,把一个对象的所有字段赋值给另外一个对象。

http://www.cnblogs.com/javastorm/archive/2012/03/14/2396419.html

 

自己写的抄的记录,原帖不能

import java.lang.reflect.Field;

public  void copyPropertysWithoutNull(Object des, Object src){        //将源拷贝到目的,NULL字段不拷贝(不同类对象,不知道能否,没有深究)
  Class clazz = des.getClass();       
  Field[] srcfields=src.getClass().getDeclaredFields();       
  for(Field field:srcfields){           
   if(field.getName().equals("serialVersionUID"))               
    continue;           
   Field f;           
   try {               
    f = clazz.getDeclaredField(field.getName());               
    f.setAccessible(true);               
    field.setAccessible(true);               
    Object obj = field.get(src);               
    if(obj!=null)                   
     f.set(des,obj);           
    }
   catch (SecurityException e) {               
    // TODO Auto-generated catch block               
    e.printStackTrace();           
    }
   catch (NoSuchFieldException e) {               
    // TODO Auto-generated catch block               
    e.printStackTrace();            }
   catch (IllegalArgumentException e) {               
    // TODO Auto-generated catch block               
    e.printStackTrace();            }
   catch (IllegalAccessException e) {               
    // TODO Auto-generated catch block               
    e.printStackTrace();            }       
   }   //end for
  }

你可能感兴趣的:(将一个对象的属性copy到另外一个对象里去,把一个对象的所有字段赋值给另外一个对象。)