Java Enum—未实现的特定接口的类型

Java Enum—未实现的特定接口的类型,java,enums,Java,Enums,我需要在api中使用外部库中的枚举,并且我需要该枚举来实现接口。由于我无法从库中修改枚举以实现特定接口,我想知道是否可以选择执行以下操作(这是一个基本示例): 从库中枚举: public enum ExampleEnumType { private long id; private String description; public long getId() { return id; } public String getDescri

我需要在api中使用外部库中的枚举,并且我需要该枚举来实现接口。由于我无法从库中修改枚举以实现特定接口,我想知道是否可以选择执行以下操作(这是一个基本示例):

从库中枚举:

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 getStaticData(){
List examples=Lists.newLinkedList();
addAll(Arrays.asList(ExampleEnumType.values());
//更多代码
返回示例;
}
我当时的想法是做以下事情,但我不确定这是否是一种选择:

public List<ExampleInterface> getExampleObjects() {
return
    Arrays.stream(ExampleEnumType.values()).<ExampleInterface>map(
        exampleEnumType -> () -> {
            return new ExampleObject(exampleEnumType.getId(), exampleEnumType.getDescription());
        }).collect(toList());
}
公共列表getExampleObjects(){
返回
Arrays.stream(ExampleEnumType.values()).map(
exampleEnumType->()->{
返回新的ExampleObject(exampleEnumType.getId(),exampleEnumType.getDescription());
}).collect(toList());
}

谢谢大家!

您可以始终将功能组合置于继承之上

公共枚举示例枚举类型示例接口适配器实现示例接口{
私有静态最终映射适配器=Collections.synchronizedMap(新的EnumMap(ExampleEnumType.class));
私有ExampleEnumType ExampleEnumType;
私有示例EnumTypeExampleInterfaceAdapter(ExampleEnumTypeEN){
这个.exampleEnumType=en;
}
公共静态示例EnumTypeExampleInterfaceAdapter getAdapter(ExampleEnumTypeEN){
返回adapters.ComputeFabSent(en,ExampleNumTypeExampleInterfaceAdapter::new);
}
@凌驾
公共示例对象createExampleObject(){
返回新的ExampleObject(en.getId(),en.getDescription());
}
公共示例EnumType getEnum(){
返回exampleEnumType;
}
}
这将创建一个实现
ExampleInterface
的新类。对于枚举的每个实例,都有相应的类实例

如果要获取枚举常量接口的实现,请使用
ExampleEnumTypeExampleInterfaceAdapter.getAdapter(ExampleEnumType.enum\u常量)


为了从
ExampleEnumTypeExampleInterfaceAdapter
对象获取枚举,请使用
yourAdapterObject.getEnum()

当然,第一个代码段是有效的,您只需创建N个与
EnumType
无关的匿名
可运行的
类。(我)不清楚你的实际目标是什么。@luk2302我更新了这个问题。目标是使用enum作为ExampleInterface类型,我不知道如何使用它。这个问题还不清楚。首先,你没有解释ID和描述来自哪里。我建议你用一些精心设计的特定场景重写你的例子。@BasilBourque我更新了问题,希望现在问题清楚了。