开发者

Strategies for converting collections from one type to another

What is the most efficient way to convert A开发者_如何转开发rrayLists with EO (Entity Object) into ArrayLists of DTO objects or ArrayLists of Ids. Please, keep in mind that every EO may consist of properties which are also EOs, or collections of EOs, which should internally be converted to DTOs, or omitted (depending on the conversion strategy). In general, a lot of boilerplate code.

wish it were as simple as:

collectionOfUsers.toArrayList<UserDTO>(); 

or..

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

of course, this could be nice as well:

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

Of course, someone should hold the mapping strategies as well, for instance a Factory or sth.

any suggestions ?


You could just use a simple interface to simulate conversion.

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;
}

Note that this is just the same as a library that implements map functionality.

In terms of efficiency, I guess you will be running into problems because entity objects will (possibly) be fetching from the database. You could make relationships eager to explore whether that made any difference.


You should create a generic method for converting from one type to another. Here is the simple interface for that:

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

You would then use that in a generic conversion method:

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;
}

One use of this may look like:

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

I use this same strategy in one of my open source projects. Have a look at JodeList on line 166 for an example. It is a bit simplified in my case because it only transforms from Jode to any type, but it should be able to be expanded to converting between any type.


Consider using Apache Commons BeanUitls.populate().

It would populate each equivalent property from a Bean to another.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜