您可以使用自定義轉換器解決這個問題。主要想法是使用ConvertUtils.register(Converter converter, Class<?> clazz)
註冊新轉換器Set
。實現您的自定義設置列表轉換器的convert(Class<T> type, Object value)
方法不是問題。
這是給你的問題簡單的例子:
ListEntity,其中有List
財產(不要忽略getter和setter方法,因爲據我所知,他們的存在是必須的):
public class ListEntity {
private List<Integer> col = new ArrayList<>();
public List<Integer> getCol() {
return col;
}
public void setCol(List<Integer> col) {
this.col = col;
}
}
SetEntity,其中有Set
屬性:
public class SetEntity {
private Set<Integer> col = new HashSet<>();
public Set<Integer> getCol() {
return col;
}
public void setCol(Set<Integer> col) {
this.col = col;
}
}
簡單的測試類,以使工作:
public class Test {
public static void main(String... args) throws InvocationTargetException, IllegalAccessException {
SetEntity se = new SetEntity();
se.getCol().add(1);
se.getCol().add(2);
ListEntity le = new ListEntity();
ConvertUtils.register(new Converter() {
@Override
public <T> T convert(Class<T> tClass, Object o) {
List list = new ArrayList<>();
Iterator it = ((Set)o).iterator();
while (it.hasNext()) {
list.add(it.next());
}
return (T)list;
}
}, List.class);
BeanUtils.copyProperties(le, se);
System.out.println(se.getCol().toString());
System.out.println(le.getCol().toString());
}
}
此代碼剪斷的主要思路:我們註冊的所有目標類List
性質轉換器,它會嘗試o
將一些對象List
。假設,即o
是一個集合,我們遍歷,然後返回新創建的列表。
因此,le
將包含1
和2
值。如果您不再需要此轉換器,則可以使用ConvertUtils.deregister()
取消註冊。
是的,但我試圖避免增加額外的另一個依賴於我的項目。 – 2014-10-20 07:13:11