情景:在開發過程中,需要將兩個對象實體的值進行對比
處理:使用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 --- :[攝影, 旅行, 家居, 做飯]
注;以上是為瞭解決問題找到的解決方案,但是具體原因並不知悉,如果大家有答案請回複我,
本人虛心請教,以上如有問題請指正。