2011-07-18 95 views
4

将ArrayLists与EO(实体对象)转换为DTO对象的ArrayLists或Ids的ArrayLists的最有效方法是什么?请记住,每个EO可能包含也是EO的属性,或EO的集合,这些集合应在内部转换为DTO,或省略(取决于转换策略)。一般来说,有很多样板代码。将集合从一种类型转换为另一种类型的策略

希望它是那么简单:

collectionOfUsers.toArrayList<UserDTO>(); 

或..

collectionOfUsers.toArrayList<IEntity>(); 
// has only an id, therefore it will be converted 
// into a collection of objects, having only an id. 
当然

,这可能是不错的还有:

collectionOfUsers.toArrayList<Long>() 
// does the same thing, returns only a bunch of ids 

当然,有人要也要保持映射策略,例如Factory或者某事物。

有什么建议吗?

回答

0

考虑使用Apache Commons BeanUitls.populate()。

它会将每个Bean的等价属性填充到另一个。

2

您可以使用简单的界面来模拟转换。

interface DTOConvertor<X,Y> { 
    X toDTO(Y y); 
} 

public static List<X> convertToDTO(Collection<Y> ys, DTOConvertor<X,Y> c) { 
    List<X> r = new ArrayList<X>(x.size()); 
    for (Y y : ys) { 
     r.add(c.toDTO(y)); 
    } 
    return y; 
} 

请注意,这与实现map功能的库完全相同。

就效率而言,我猜你会遇到问题,因为实体对象将(可能)从数据库中提取。你可以建立人际关系,以探索这是否有所作为。

2

您应该创建一种从一种类型转换为另一种类型的通用方法。以下是一个简单的界面:

public interface XFormer<T,U> { 
    public T xform(U item); 
} 

你可以这样使用,在一个通用的转换方法:

public static <T, U> List<T> xForm(List<U> original, XFormer<T, U> strategy) { 
    List<U> ret = new ArrayList<U>(original.size()); 
    for (U item: original) { 
     ret.add(strategy.xform(item)); 
    } 
    return ret; 
} 

的一种用途可能看起来像:

List<String> original; 
List<Long> xFormed = xForm(original, new XFormer<Long, String>() { 
         public Long xForm(String s) { 
          return Long.parseLong(s); 
         } 
        }); 

我用在我的一个开源项目中也采用了同样的策略。例如,查看166行的JodeList。这在我的情况下有点简化,因为它只是从Jode转换到任何类型,但它应该能够扩展到任何类型之间的转换。

相关问题