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_MAPPER
does not accept concrete subclasses SomeOtherObject
and SomeObject
as valid signatures for the abstract method.
Can this not be done?