Search code examples
javagenericsmappingdozer

Java Generic Class Mapper Many to one


I've realized a little framework to Convert a generic Entity of type A to one of Type B.

So I created an interface:

public interface IConvert<A,B> {
    public B convert (A entity);
    public List<B> convertList(List<A> entitylist);
}

And an abstract class to generalize the convertList method:

public abstract class AbstractConverter<A,B> implements IConvert<A, B> {

    @Override
    public abstract B convert(A entity) ;

    @Override
    public List<B> convertList(List<A> entitylist) {
        List<B> bs=new ArrayList<B>();
        for (A a : entitylist) {
            bs.add(convert(a));
        }
        return bs;
    }    
}

Suppose we have to map a BClass instance to an AClass instance:

public class AClassConverter extends AbstractConverter<BClass, AClass>{

    @Override
    public AClass convert(BClass entity) {
        return new AClass(); //BClass to AClass mapping
    }
}

I can simply define a new class AClassConverter, extending the abstract one and implement the specific convert method. The convertList method is free.

What I'm trying to understand is how to generalize an m to one type converter without have to always reimplement the convertList method for entity:

public class AClassConverter extends AbstractConverter<BClass, AClass> {

    @Override
    public AClass convert(BClass entity) {
    return new AClass(); //BClass to AClass mapping
    }

    public AClass convert(CClass entity) {
        return new AClass(); //CClass to AClass mapping
    }

    public List<AClass> convert(List<CClass> entityList) {
        //foreach > call convert(c);
        //return aClassList;
    }
}

Consider that AClass, BClass, and CClass don't extend any common class (apart from Object). And AClass, BClass, and CClass don't have cross reference (AClass is unaware of BClass so I can't define in BClass something as convertToAClass...).

I'd need something as:

public class AClassConverter extends AbstractConverter<BClass, AClass> , AbstractConverter<CClass, AClass>

!!!

Regards, and sorry for the confusion.


Solution

  • Due to the lack of multiple inheritance in java it cannot be done quite that easily.

    However, at the cost of a slightly less elegant solution, you could refactor your code pulling the convertList method into a static helper class.

    Maybe like so:

    public final class ConverterHelper {
       private ConverterHelper() {}
    
       public static <A,B> List<B> convertList(IConvert<A,B> converter, List<A> list)
       {
          List<B> bs=new ArrayList<B>();
          for (A a : list) {
             bs.add(converter.convert(a));
          }
          return bs;
       }
    }
    

    You would then always have to use the static helper method if you wanted to convert lists.