[英]Enum - type of a specific interface without implementing it
我需要在 api 中使用来自外部库的枚举,并且我需要该枚举来实现接口。 由于我无法从库中修改 Enum 以实现特定接口,我想知道是否可以选择执行以下操作(这是一个基本示例):
库中的枚举:
public enum ExampleEnumType {
private long id;
private String description;
public long getId() {
return id;
}
public String getDescription() {
return description;
}
}
我需要的是实现接口,但我无法:
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());
}
}
我需要 enum 中的值是 ExampleInterface 类型(作为实现接口)才能在方法中使用它们:
public List<ExampleInterface> getStaticData() {
List<ExampleInterface> examples = Lists.newLinkedList();
examples.addAll(Arrays.asList(ExampleEnumType.values()));
//more code
return examples;
}
我在想的是做以下事情,但我不确定它是否是一个选项:
public List<ExampleInterface> getExampleObjects() {
return
Arrays.stream(ExampleEnumType.values()).<ExampleInterface>map(
exampleEnumType -> () -> {
return new ExampleObject(exampleEnumType.getId(), exampleEnumType.getDescription());
}).collect(toList());
}
谢谢!
您始终可以在 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;
}
}
这将创建一个新的 class 实现ExampleInterface
。 对于枚举的每个实例,您都有一个对应的 class 实例。
如果要获取枚举常量的接口实现,请使用ExampleEnumTypeExampleInterfaceAdapter.getAdapter(ExampleEnumType.ENUM_CONSTANT)
。
为了从ExampleEnumTypeExampleInterfaceAdapter
object 中获取枚举,请使用yourAdapterObject.getEnum()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.