使用BeanUtils.describe將對象轉換成Map時,數組欄位的值只擷取到第一個元素

來源:互聯網
上載者:User

情景:在開發過程中,需要將兩個對象實體的值進行對比

處理:使用BeanUtils.describe將兩個對象轉換成Map進行遍曆對比資料

問題:發現BeanUtils.describe轉換後的Map的泛型是<String,String>此時擷取到的欄位如果是數群組類型的話只擷取了第一個元素

解決:使用PropertyUtils.describe方法的到的Map的泛型是<String,Object>此時可以正常擷取到資料


代碼如下:

@Datapublic class Person implements Serializable {//實體    /**     *      */    private static final long serialVersionUID = 3193754045080382621L;    private String            name;    private Integer           sex;    private Integer           age;    private String            school;    private String[]          hobby;    private List<String>      place;}

    public static void main(String[] args) {//測試        Person p = new Person();        p.setName("Akili");        p.setSex(1);        p.setAge(24);        p.setSchool(null);        p.setHobby(new String[] { "攝影", "旅行", "家居", "做飯" });        p.setPlace(Lists.newArrayList("北京","深圳","廣州","北海"));        Map<String, String> beanLog = new HashMap<String, String>();        Map<String, Object> propertyLog = new HashMap<String, Object>();        try {            beanLog = BeanUtils.describe(p);        } catch (Exception e) {            LOG.info("error message", e);            return;        }        try {            propertyLog = PropertyUtils.describe(p);        } catch (Exception e) {            LOG.info("error message", e);            return;        }        if (beanLog != null && propertyLog != null) {            for (Map.Entry<String, String> entry : beanLog.entrySet()) {                Map<String, String> temp = new HashMap<String, String>();                if (entry.getKey().equals("hobby")) {                    System.out.println("beanLog hobby --- :" + entry.getValue());                    System.out.println("propertyLog hobby --- :" + Arrays.toString((String[])propertyLog.get(entry.getKey())));                }                if(entry.getKey().equals("place")){                    System.out.println("beanLog place --- :" + entry.getValue());                    System.out.println("propertyLog place --- :" + propertyLog.get(entry.getKey()));                }            }        }    }


結果:beanLog place --- :北京propertyLog place --- :[北京, 深圳, 廣州, 北海]beanLog hobby --- :攝影propertyLog hobby --- :[攝影, 旅行, 家居, 做飯]


注;以上是為瞭解決問題找到的解決方案,但是具體原因並不知悉,如果大家有答案請回複我,

        本人虛心請教,以上如有問題請指正。










聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.