1

My code consumes two libraries - LibraryA and LibraryB.

LibraryA has defined an enum :

public enum EnumA {
    FIRST,
    SECOND;
}

LibraryB has also defined an enum :

public enum EnumB {
    ONE,
    TWO;
}

How can I aggregate these two enums in my code into a single type - class or enum, say MyAggregatedEnum so that I can enumerate on values defined in both EnumA and EnumB.

Edit : Editing to include a more concrete use case. I want to have a Map<MyAggregatedEnum, TypeHandler>. This map will be created statically. For each individual value, there can be a different TypeHandler. Eg. for FIRST, there can be a type handler - HandlerFirst, for ONE, there can be a type handler - HandlerOne, and so on.

Apologies for not adding this in the first draft itself.

I can't make library enums to implement some common interface.

user2653062
  • 697
  • 1
  • 9
  • 16

1 Answers1

4

This won't work with dynamic values; but as aggregateEnumList is created statically, it may solve your current problem.

interface MyAggregatedEnum {
    String getValue();
}

And

List<MyAggregatedEnum> aggregateEnumList = 
             List.of(EnumA.FIRST::getValue, EnumB.ONE::getValue);

printValues(aggregateEnumList);

The getValue method referenced in the last snippet is not from the same API, but it provides an implementation for MyAggregatedEnum.getValue() (which doesn't have to be named getValue, by the way)


EDIT: following the edited question, I'd suggest that your solution is as simple as using the Enum type itself:

Map<Enum<?>, TypeHandler> myMap = new HashMap<>();
myMap.put(EnumA.FIRST, someHandler);
myMap.put(EnumB.ONE, someOtherHandler);

...

TypeHandler firstHandler = myMap.get(EnumA.FIRST);
TypeHandler oneHandler = myMap.get(EnumB.ONE);
ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • Thanks for the input, have edited the question to include more concrete use case. – user2653062 Feb 21 '20 at 10:58
  • 1
    @user2653062 That changes the question quite a bit. I've edited the answer, see the bottom section – ernest_k Feb 21 '20 at 11:18
  • just to clarify `TypeHandler` is not a class from standard jdk. It is a class from iBatis or some other third party library. – Diablo Dec 08 '20 at 09:44