gpt4 book ai didi

java - 如何将枚举常量转换为其字段值的键值对?

转载 作者:行者123 更新时间:2023-12-02 10:57:37 25 4
gpt4 key购买 nike

我有一个 Java 枚举类,其中包含多个枚举常量,每个常量定义有多个字段。

我希望能够将枚举常量转换为包含字段名称和值的键值对列表。

困难在于创建一个设置,该设置允许用户只需要添加新的枚举常量,甚至向每个常量添加新字段,而不需要使用此数据的代码知道哪些字段将存在。

public enum Stuff
{
ORDINAL_ZERO( "Zero's identifier", "Zero's value A", "Zero's value B" ),
ORDINAL_ONE( "One's identifier", "One's value A", "One's value B" );

private String identifer;
private String valueA;
private String valueB;

Stuff( String identifier, String valueA, String valueB )
{
this.identifier = identifier;
this.valueA = valueA;
this.valueB = valueB;
}

public static Stuff getStuffForIdentifier( String identifier )
{
for ( Stuff stuff : values() )
{
if ( stuff.getIdentifier().equalsIgnoreCase( identifier ) )
return stuff;
}
}

public static Map<String, String> getStuffForIdentifierAsMap( String identifier )
{
TODO: return a key-value pair map of a single enum constant where I can iterate through the keys and get their values without knowing what all fields are defined ahead of time i.e. if we asked for a map of the 0 ordinal constant's fields:
Map<String, String> map = new HashMap<String, String>();
map.put("identifier", "Zero's identifer");
map.put("valueA", "Zero's value A");
map.put("valueB", "Zero's value B");
return map;
}
}

最佳答案

您可以迭代 Stuff.values() 以找到具有正确标识符的值

public static Map<String, Object> getStuffForIdentifierAsMap(String identifier) 
throws IllegalAccessException {
for (Stuff stuff : Stuff.values()) {
if(stuff.getIdentifier().equals(identifier)) {
...
}

注意:每次调用该方法时调用 Stuff.values() 都是邪恶的,因为它每次都会创建数组的新副本。在生产代码中,您可以通过一些缓存来避免这种情况。

然后,您可以像这样迭代类的字段:

private static Map<String, Object> dumpValues(Stuff stuff) throws IllegalAccessException {
Map<String, Object> map = new HashMap<String, Object>();
for (Field field : stuff.getClass().getDeclaredFields()) {
map.put(field.getName(), field.get(stuff));
}
return map;
}

测试:

public static void main(String[] args) throws Exception {
Map<String, Object> props = getStuffForIdentifierAsMap("Zero's identifier");

for (Map.Entry<String, Object> entry : props.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}

输出:

ORDINAL_ONE : ORDINAL_ONE
identifier : Zero's identifier
valueB : Zero's value B
valueA : Zero's value A
ORDINAL_ZERO : ORDINAL_ZERO
$VALUES : [Lcom.denodev.Stuff;@60e53b93

注意:您可以从类本身获得一些额外的属性。

关于java - 如何将枚举常量转换为其字段值的键值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51597789/

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