zoukankan      html  css  js  c++  java
  • 将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

  • 相关阅读:
    【高斯消元】BZOJ 1770: [Usaco2009 Nov]lights 燈
    【高斯消元】Poj 1222:EXTENDED LIGHTS OUT
    【高斯消元】BZOJ 1013: [JSOI2008]球形空间产生器sphere
    【数学】[BZOJ 3884] 上帝与集合的正确用法
    【数学/扩展欧几里得/线性求逆元】[Sdoi2008]沙拉公主的困惑
    【数学/扩展欧几里得/Lucas定理】BZOJ 1951 :[Sdoi 2010]古代猪文
    【扩展欧几里得】Bzoj 1407: [Noi2002]Savage
    [51nod2935] 土地划分
    [51nod2982] 大逃杀
    [BZOJ1005] HNOI2008 明明的烦恼
  • 原文地址:https://www.cnblogs.com/lanliying/p/5798482.html
Copyright © 2011-2022 走看看