将带有 EO(实体对象)的 ArrayList 转换为 DTO 对象的 ArrayList 或 ID 的 ArrayList 的最有效方法是什么。请记住,每个 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
当然,也应该有人掌握映射策略,比如工厂什么的。
有什么建议吗?
最佳答案
您可以只使用一个简单的界面来模拟转换。
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
功能的库相同。
在效率方面,我猜你会遇到问题,因为实体对象(可能)会从数据库中获取。您可以让关系渴望探索这是否有任何不同。
关于java - 将集合从一种类型转换为另一种类型的策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6733133/