gpt4 book ai didi

java - 迭代通用枚举实例

转载 作者:行者123 更新时间:2023-12-02 02:20:03 29 4
gpt4 key购买 nike

正如您在下面看到的,我有三个声明的枚举,每个类都有一个名为 getEnumByName() 的方法,该方法恢复名称并返回具有该名称的枚举。

我注意到我在每个枚举上复制了此方法的相同功能。

有没有办法将此方法更改为通用方法,该方法接收给定枚举的类型并执行相同的逻辑?

public class Enums {

public enum A {
APPLY("Apply", "abcde");

private String id;
private String name;

A(String name, String id) {
this.name = name;
this.id = id;
}

public static A getEnumByName(String name) throws Exception {
for (A instance : A.values()) {
if (instance.getName().equals(name)) return instance;
}
throw new Exception("There is no operations matches :" + name);
}

public String getName() {
return name;
}

public String getId() {
return id;
}
}

public enum B {
APPLY("Apply", "1"),
SAVE("Save", "2"),
REVERT("Revert", "2"),
REVERT_CHILD("Revert->Revert", "4"),
REVERT_APPLY("Revert->Revert Apply", "5"),
SYNC("Sync", "6"),
OPERATIONS("Operations", "7"),
IMPORT("Import", "8"),
EXPORT("Export", "9"),
DIFF("Diff", "10");

private String id;
private String name;

B(String name, String id) {
this.name = name;
this.id = id;
}

public static B getEnumByName(String name) throws Exception {
for (B instance : B.values()) {
if (instance.getName().equals(name)) return instance;
}
throw new Exception("There is no operations matches :" + name);
}

public String getName() {
return name;
}

public String getId() {
return id;
}
}

public enum C {
UPDATE_POLICES("Update Policies", "A"),
OPERATIONS("Operations", "B"),
IMPORT_CONFIGURATION_FILE("Import Configuration File", "c"),
EXPORT_CONFIGURATION_FILE("Export Configuration File", "d"),
EXPORT_LOG_SUPPORT_FILE("Export Log Support File", "f"),
EXPORT_TECHNICAL_SUPPORT_FILE("Export Technical Support File", "g"),
UPDATE_SOFTWARE_VERSION("Update Software Version", "g"),
UPDATE_SECURITY_SINGAUTES("Update Security Signatures", "h"),
DIFF("Diff", "k");

private String id;
private String name;

C(String name, String id) {
this.name = name;
this.id = id;
}

public static C getEnumByName(String name) throws Exception {
for (C instance : C.values()) {
if (instance.getName().equals(name)) return instance;
}
throw new Exception("There is no operations matches :" + name);
}

public String getName() {
return name;
}

public String getId() {
return id;
}
}
}

最佳答案

一种选择是让它们全部实现一个名为 Named 的通用接口(interface):

interface Named {
String getName();
}

现在您可以创建一个像这样的通用方法:

static <E extends Enum<E> & Named> E getEnumByName(Class<E> enumClass, String name) throws Exception {
return Arrays.stream(enumClass.getEnumConstants())
.filter(e -> e.getName().equals(name))
.findAny()
.orElseThrow(() -> new Exception("There is no operations matches :" + name));
}

并这样调用它:

A a = getEnumByName(A.class, "Apply");

关于java - 迭代通用枚举实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48636189/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com