2
我使用BeanUtils.setProperty來設置bean的深層屬性。設置bean的深層屬性,如果需要的話創建中間實例
Home home = new Home() ;
String path = "home.family.father.age";
Integer value = 40;
BeanUtils.setProperty(home, path, value);
// Does the same as home.getHome().getFamily().getFather().setAge(value);
// But stops on null (instead of throwing an NPE).
的BeanUtils的行爲是什麼也不做,如果中介屬性之一是null
。例如在我的情況下,home
的family
屬性是null
,沒有任何反應。如果我做
family = new Family();
然後father
將是無效和我必須得初始化。很顯然,我的真實用例更復雜,具有許多動態屬性(還有索引的)。
有沒有辦法告訴BeanUtils實例化中間成員?我知道一般情況下這是不可能的(因爲財產的具體類型可能不知道)。但在我的情況下,所有的屬性都有具體的類型,並且是合適的bean(使用公共無參數構造函數)。所以這是可能的。
我想確保在滾動我自己之前還沒有現有的解決方案(使用BeanUtils或其他)。