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

  • 相关阅读:
    回调函数案例(二)
    回调函数案例(一)
    liteos学习文档liteos.github.io
    HeapAlloc、GlobalAlloc和new等内存分配有什么区别么?
    C语言中字符数组和字符串指针分析
    socket 连接,使得地址马上可以重用
    shutdown 和closesocket
    IP地址转换成Long型数字的算法
    WSAStartup( )
    关于完成端口IOCP异步接收连接函数AcceptEx注意事项
  • 原文地址:https://www.cnblogs.com/lanliying/p/5798482.html
Copyright © 2011-2022 走看看