码迷,mamicode.com
首页 > 其他好文 > 详细

将src非空的属性注入到des中

时间:2016-08-23 11:39:49      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

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

将src非空的属性注入到des中

标签:

原文地址:http://www.cnblogs.com/lanliying/p/5798482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!