0

I have a lot of different objects which are being mapped so I've written a bunch of static mapping methods and one giant switch-case method which takes the type (a built-in field) and then uses the specialized mapping function.

Example:

public static SomeOtherObject mapFrom(SomeObject someObject) {
    //... mapping logic
    return someOtherObjectInstance;
}

//... a bunch of those

// root/main mapper
public static SomeOtherObjectBase mapFrom(SomeObjectBase someObjectBase) {
    switch(someObjectBase.getType()) {
        case SOME_TYPE: return mapFrom((SomeObject)someObjectBase);
        //...
    }
}

I then thought that I could probably convert this to an enum where each enumeration would be a mapper and would be bound to the type, thus avoiding a switch-case... something like this:

public enum SomeObjectMappers {
    SOME_TYPE_MAPPER(SOME_TYPE) {
        @Override
        SomeOtherObject mapFrom(SomeObject someObject) {
            //... mapping logic
            return someOtherObjectInstance;
        }
    },
    //... a bunch of those
    ;

    private final Type type;

    //constructor, getters...

    abstract <T extends SomeOtherObjectBase, U extends SomeObjectBase> T mapFrom(U obj);

    public static SomeOtherObjectBase mapFrom(SomeObjectBase obj) {
        return Arrays.stream(values())
                    .filter(v -> v.getType() == type)
                    .map(m -> m.mapFrom(obj))
                    .findFirst()
                    .orElse(null);
    }
}

However this does not really compile/work as for some reason mapper implementation in SOME_TYPE_MAPPERdoes not accept concrete subclasses SomeOtherObject and SomeObject as valid signatures for the abstract method.

Can this not be done?

hlepme
  • 97
  • 12
  • I see no logical reasy why you would even want to consider to use an Enum as a type containing business logic, let alone a mapper. – Stultuske Aug 08 '18 at 09:24
  • Because generic enums are not currently possible you have to hack your way arround. Maybe have a look at this [question](https://stackoverflow.com/questions/11490485/how-to-implement-enum-with-generics/11490505) – Lino Aug 08 '18 at 09:29

0 Answers0