我有许多不同的对象正在被映射,所以我写了一堆静态映射方法和一个巨型开关案例方法,该方法采用类型(内置字段),然后使用专门的映射功能
示例:
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);
//...
}
}
然后我以为我可以将其转换为一个枚举,其中每个枚举将是一个映射器,并且将被绑定到该类型,从而避免了切换情况……诸如此类:
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);
}
}
但是由于某些原因,SOME_TYPE_MAPPER
中的映射器实现不接受具体的子类SomeOtherObject
和SomeObject
作为抽象方法的有效签名,因此它实际上不能编译/工作。
这不能完成吗?