2014-10-17 142 views
3

我使用BeanUtils.copyProperties轉換兩個bean。有沒有辦法使用BeanUtils.copyProperties將Set映射到List?

BeanUtils.copyProperties(organization, dtoOrganization); 

我想有一個豆一List和另一個爲Set

第一個bean:

public class Form { 

    private Set<Organization> organization; 

} 

二豆:

public final class DTOForm { 

    private List<DTOOrganization> organization; 

} 

結果是一個例外,因爲在這裏說: argument type mismatch by Using BeanUtils.copyProperties

是否可以定製BeanUtils.copyProperties才達到的呢?

回答

1

您可以使用自定義轉換器解決這個問題。主要想法是使用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將包含12值。如果您不再需要此轉換器,則可以使用ConvertUtils.deregister()取消註冊。

1

從一組一種類型的轉換爲另一種類型的列表是一個相當的拉伸。

雖然你可以通過創建自定義的JavaBean PropertyEditor來實現它,我寧願使用一個映射框架像Dozer

+0

是的,但我試圖避免增加額外的另一個依賴於我的項目。 – 2014-10-20 07:13:11

相關問題