zoukankan      html  css  js  c++  java
  • Spring、Commons的BeanUtils.copyProperties用法

    如果两个对象A、B的大部分属性的名字都一样,此时想将A的属性值复制给B,一个一个属性GETSET代码量太大,可以通过复制属性的方式减小工作量,同时代码看起来更加简洁明了,复制属性可以用Spring或者Commons下的Beanutils.copyProperties方法。这种复制只是简单的浅复制。

    1.Spring BeanUtils.copyProperties

    public void saveFeedback(CustomerFeedbackTemp customerFeedbackTemp)
     {
           CustomerFeedbackInfo feedBackInfo = new CustomerFeedbackInfo();
           BeanUtils.copyProperties(customerFeedbackTemp,feedBackInfo); 
    ......
    }

    上面部分代码将页面传入的CustomerFeedbackTemp对象的属性复制到CustomerFeedbackInfo对象里。方便吧。

    2.Common BeanUtils.copyProperties

    public void saveFeedback(CustomerFeedbackTemp customerFeedbackTemp)
     {
           CustomerFeedbackInfo feedBackInfo = new CustomerFeedbackInfo();
           BeanUtils.copyProperties(feedBackInfo, customerFeedbackTemp);
           ...... 
     } 

    用法跟Spring的差不多,只是参数位置不一样。

    除BeanUtils外还有一个名为PropertyUtils的工具类,它也提供copyProperties()方法,作用与 BeanUtils的同名方法十分相似,主要的区别在于后者提供类型转换功能,即发现两个JavaBean的同名属性为不同类型时,在支持的数据类型范围内进行转换,而前者不支持这个功能,但是速度会更快一些。BeanUtils支持的转换类型如下:

        * java.lang.BigDecimal
        * java.lang.BigInteger
        * boolean and java.lang.Boolean
        * byte and java.lang.Byte
        * char and java.lang.Character
        * java.lang.Class
        * double and java.lang.Double
        * float and java.lang.Float
        * int and java.lang.Integer
        * long and java.lang.Long
        * short and java.lang.Short
        * java.lang.String
        * java.sql.Date
        * java.sql.Time
        * java.sql.Timestamp 
    

    这里要注意一点,java.util.Date是不被支持的,而它的子类java.sql.Date是被支持的。因此如果对象包含时间类型的属性,且希望被转换的时候,一定要使用java.sql.Date类型。否则在转换时会提示argument mistype异常。

  • 相关阅读:
    中译英6
    中译英5
    中译英4
    B5
    BEC listen and translation exercise 37
    BEC listen and translation exercise 36
    中译英2
    PyQt(Python+Qt)学习随笔:Designer中ItemViews类部件的frameShadow属性
    第15.16节 PyQt(Python+Qt)入门学习:PyQt中的信号(signal)和槽(slot)机制以及Designer中的使用
    PyQt(Python+Qt)学习随笔:Designer中ItemViews类部件frameShape属性
  • 原文地址:https://www.cnblogs.com/foxting/p/8442122.html
Copyright © 2011-2022 走看看