将src非空的属性注入到des中
package lizikj.bigwheel.common.vo.merchandise.util;
import java.lang.reflect.Field;
import lizikj.bigwheel.common.vo.merchandise.Merchandise;
public class ObjUtils {
/**
* 将src非空的属性注入到des中
* @param des
* @param src
*/
public static void copyPropertysWithoutNull(Object des, Object src){
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) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Merchandise origin=new Merchandise();
origin.setBarCode("2");
origin.setBrowseNum(1);
origin.setCategoryId(1);
origin.setDescribe(null);
origin.setBrand(null);
Merchandise destination=new Merchandise();
destination.setBarCode(null);
destination.setCategoryId(2);
destination.setDescribe("5555");
destination.setBrand("ttt");
ObjUtils.copyPropertysWithoutNull(destination, origin);
System.out.println(destination.getBarCode());
System.out.println(destination.getDescribe());
System.out.println(destination.getBrand());
System.out.println(destination.getCategoryId());
}
}
忘记在那里找的了
import Java.lang.reflect.Field;
public class BeanUtils {
public static void copyPropertysWithoutNull(Object des, Object src) throws Exception{
Class<?> clazz = des.getClass();
Field[] srcfields=src.getClass().getDeclaredFields();
for(Field field:srcfields){
if(field.getName().equals("serialVersionUID"))
continue;
Field f =clazz.getDeclaredField(field.getName());
field.setAccessible(true);
Object obj = field.get(src);
if(obj!=null)
f.set(des,field.get(src));
}
}
}
来自:http://blog.csdn.net/wutongyu344/article/details/7353951