Reputation: 2135
I need to use an Enum from an external library in my api and i need that enum to implement an interface. As I am not able to modify the Enum from the library to implement a specific interface, i am wondering if it is an option to do the following (it's a basic example):
Enum from library:
public enum ExampleEnumType {
private long id;
private String description;
public long getId() {
return id;
}
public String getDescription() {
return description;
}
}
What i would need is to implement the interface, but i am not able to:
public enum ExampleEnumType implements ExampleInterface {
private long id;
private String description;
public long getId() {
return id;
}
public String getDescription() {
return description;
}
@Override
public ExampleObject createExampleObject() {
return new ExampleObject(getId(), getDescription());
}
}
I need the values from enum to be of type ExampleInterface (as implementing the interface) to use them in a method:
public List<ExampleInterface> getStaticData() {
List<ExampleInterface> examples = Lists.newLinkedList();
examples.addAll(Arrays.asList(ExampleEnumType.values()));
//more code
return examples;
}
What i was thinking is doing the following, but i am not sure if it is an option:
public List<ExampleInterface> getExampleObjects() {
return
Arrays.stream(ExampleEnumType.values()).<ExampleInterface>map(
exampleEnumType -> () -> {
return new ExampleObject(exampleEnumType.getId(), exampleEnumType.getDescription());
}).collect(toList());
}
Thank you!
Upvotes: 0
Views: 84
Reputation: 16348
You can always feature composition over inheritance:
public enum ExampleEnumTypeExampleInterfaceAdapter implements ExampleInterface {
private static final Map<ExampleEnumType,ExampleEnumTypeExampleInterfaceAdapter> adapters=Collections.synchronizedMap(new EnumMap<>(ExampleEnumType.class));
private ExampleEnumType exampleEnumType;
private ExampleEnumTypeExampleInterfaceAdapter(ExampleEnumType en){
this.exampleEnumType=en;
}
public static ExampleEnumTypeExampleInterfaceAdapter getAdapter(ExampleEnumType en){
return adapters.computeIfAbsent(en,ExampleEnumTypeExampleInterfaceAdapter::new);
}
@Override
public ExampleObject createExampleObject() {
return new ExampleObject(en.getId(), en.getDescription());
}
public ExampleEnumType getEnum(){
return exampleEnumType;
}
}
This creates a new class implementing ExampleInterface
. For every instance of the enum, you have a corresponding instance of the class.
If you want to get the implementation of the interface for an enum constant, use ExampleEnumTypeExampleInterfaceAdapter.getAdapter(ExampleEnumType.ENUM_CONSTANT)
.
In order to get the enum from a ExampleEnumTypeExampleInterfaceAdapter
object, use yourAdapterObject.getEnum()
Upvotes: 1