英文:
How can we store String to Enum classes map
问题
I have multiple enum classes . For example
public class enum Animal {
DOG,
LION;
}
public class enum Bird {
OSTRICH,
CROW };
}
I want to have a Map<String, Enums > where i can store these enum classes as values and then fetch them based on keys . For example
Map<String, Enumclass> such that it gives me the Enum when i pass the key to the Map. For example map.get("Animal") should return me the enum Animal and then i can do operations like Animals.valueOf();
I was able to store the enums in a private Map<String, Class<? extends Enum>> Map; but not able to retreive and cast it back to the proper enum classes. Is it possible to do this
英文:
I have multiple enum classes . For example
public class enum Animal {
DOG,
LION;
}
public class enum Bird {
OSTRICH,
CROW };
}
I want to have a Map<String, Enums > where i can store these enum classes as values and then fetch them based on keys . For example
Map<String, Enumclass> such that it gives me the Enum when i pass the key to the Map. For example map.get("Animal") should return me the enum Animal and then i can do operations like Animals.valueOf();
I was able to store the enums in a private Map<String, Class<? extends Enum>> Map;
but not able to retreive and cast it back to the proper enum classes. Is it possible to do this
答案1
得分: 3
You will need to have your enums implement a common interface like so:
import java.util.*;
public class Zoo {
private static final Map<String, ZooAnimal> animals;
static {
Map<String, ZooAnimal> tmp = new HashMap<>();
tmp.put("CHEETAH", Cat.CHEETAH);
tmp.put("LION", Cat.LION);
tmp.put("PANTHER", Cat.PANTHER);
tmp.put("TIGER", Cat.TIGER);
tmp.put("HAWK", Bird.HAWK);
tmp.put("OSTRICH", Bird.OSTRICH);
tmp.put("OWL", Bird.OWL);
animals = Collections.unmodifiableMap(tmp);
}
public static void main(String[] args) {
ZooAnimal animal = animals.get("PANTHER");
if (animal != null && animal instanceof Cat) {
// A panther is a cat
System.out.printf("A %s is a cat%n", animal.getName().toLowerCase());
}
}
private interface ZooAnimal {
String getName();
}
public enum Cat implements ZooAnimal {
CHEETAH, LION, PANTHER, TIGER;
@Override
public String getName() {
return this.name();
}
};
public enum Bird implements ZooAnimal {
HAWK, OSTRICH, OWL;
@Override
public String getName() {
return this.name();
}
};
}
If you want the values, you can use the generic Enum
class:
import java.util.*;
public class Zoo {
private static final Map<String, Class<? extends Enum<?>>> animals;
static {
Map<String, Class<? extends Enum<?>>> tmp = new HashMap<>();
tmp.put("BIRD", Bird.class);
tmp.put("CAT", Cat.class);
animals = Collections.unmodifiableMap(tmp);
}
public static void main(String[] args) {
Class<? extends Enum<?>> animal = animals.get("CAT");
// Print the values
for (Enum<?> c : animal.getEnumConstants()) {
System.out.println(c.name()); // CHEETAH, LION, PANTHER, TIGER
}
}
public enum Cat {
CHEETAH, LION, PANTHER, TIGER;
};
public enum Bird {
HAWK, OSTRICH, OWL;
};
}
英文:
You will need to have your enums implement a common interface like so:
import java.util.*;
public class Zoo {
private static final Map<String, ZooAnimal> animals;
static {
Map<String, ZooAnimal> tmp = new HashMap<>();
tmp.put("CHEETAH", Cat.CHEETAH);
tmp.put("LION", Cat.LION);
tmp.put("PANTHER", Cat.PANTHER);
tmp.put("TIGER", Cat.TIGER);
tmp.put("HAWK", Bird.HAWK);
tmp.put("OSTRICH", Bird.OSTRICH);
tmp.put("OWL", Bird.OWL);
animals = Collections.unmodifiableMap(tmp);
}
public static void main(String[] args) {
ZooAnimal animal = animals.get("PANTHER");
if (animal != null && animal instanceof Cat) {
// A panther is a cat
System.out.printf("A %s is a cat%n", animal.getName().toLowerCase());
}
}
private interface ZooAnimal {
String getName();
}
public enum Cat implements ZooAnimal {
CHEETAH, LION, PANTHER, TIGER;
@Override
public String getName() {
return this.name();
}
};
public enum Bird implements ZooAnimal {
HAWK, OSTRICH, OWL;
@Override
public String getName() {
return this.name();
}
};
}
If you want the values, you can use the generic Enum
class:
import java.util.*;
public class Zoo {
private static final Map<String, Class<? extends Enum<?>>> animals;
static {
Map<String, Class<? extends Enum<?>>> tmp = new HashMap<>();
tmp.put("BIRD", Bird.class);
tmp.put("CAT", Cat.class);
animals = Collections.unmodifiableMap(tmp);
}
public static void main(String[] args) {
Class<? extends Enum<?>> animal = animals.get("CAT");
// Print the values
for (Enum<?> c : animal.getEnumConstants()) {
System.out.println(c.name()); // CHEETAH, LION, PANTHER, TIGER
}
}
public enum Cat {
CHEETAH, LION, PANTHER, TIGER;
};
public enum Bird {
HAWK, OSTRICH, OWL;
};
}
答案2
得分: 0
* 更新我的答案,因为问题附带了更多解释。
我将提供另一种方法,即向枚举添加另一个维度以指示动物类型,在这种情况下,您无需转换为多个枚举:
public enum AnimalType
{
BIRD, CAT;
}
public enum Animal
{
CHEETAH(AnimalType.CAT, "猎豹"),
LION(AnimalType.CAT, "狮子"),
HAWK(AnimalType.BIRD, "鹰"),
OWL(AnimalType.BIRD, "猫头鹰");
private AnimalType type;
private String name;
Animal(AnimalType type, String name) {
this.type = type;
this.name = name;
}
public String getName() {
return name;
}
public AnimalType getType() {
return type;
}
public static Optional<Animal> fromName(String name) {
return Arrays.stream(Animal.values())
.filter(a -> a.name.equals(name))
.findFirst();
}
public static List<Animal> fromType(AnimalType type) {
return Arrays.stream(Animal.values())
.filter(a -> a.type == type))
.collect(Collectors.toList());
}
}
英文:
* Updating my answer since the question is updated with more explanations.
I'm going to provide another approach which is adding another dimension to the Enum to indicate the Animal type, and in this case you don't need to cast to multiple Enums:
public enum AnimalType
{
BIRD, CAT;
}
public enum Animal
{
CHEETAH(AnimalType.CAT, "Cheetah"),
LION(AnimalType.CAT, "Lion"),
HAWK(AnimalType.BIRD, "Hawk"),
OWL(AnimalType.BIRD, "Owl");
private AnimalType type;
private String name;
Animal(AnimalType type, String name) {
this.type = type;
this.name = name;
}
public String getName() {
return name;
}
public AnimalType getType() {
return type;
}
public static Optional<Animal> fromName(String name) {
return Arrays.stream(Animal.values())
.filter(a -> a.name.equals(name))
.findFirst();
}
public static List<Animal> fromType(AnimalType type) {
return Arrays.stream(Animal.values())
.filter(a -> a.type == type))
.collect(Collectors.toList());
}
}
答案3
得分: 0
以下是翻译好的部分:
- "There doesn't appear to be an exact solution to what you're looking to achieve." -> "似乎没有确切的解决方案来实现你所希望的。"
- "Essentially, I believe that since an enum is considered a static object, you cannot cast the static reference into a new object." -> "基本上,我认为由于 enum 被视为 static 对象,你无法将静态引用转换为新对象。"
- "You would have to use a Class<Animal> type." -> "你需要使用 Class<Animal> 类型。"
- "And, at that rate, you're better off just utilizing the Enum class." -> "而且,在这种情况下,最好直接使用 Enum 类。"
- "Here is a tutorial on Java reflection with enums, for this specific requirement." -> "这里有一个关于在特定需求下使用 enums 的Java反射教程。"
- "Examining Enums (The Java™ Tutorials > The Reflection API > Arrays and Enumerated Types)" -> "查看Enums (Java™教程 > 反射API > 数组和枚举类型)"
- "Since you know that your map values are going to be enum objects, you can utilize the Enum#valueOf method, to obtain a single value." -> "由于你知道你的映射值将是 enum 对象,你可以利用 Enum#valueOf 方法来获取单个值。"
- "If you want a list of values, similar to the values method, you can use an array of Enum and utilize the Class#getEnumConstants." -> "如果你想要一个类似于 values 方法的值列表,你可以使用 Enum 数组并利用 Class#getEnumConstants。"
- "
java\nMap<String, Class<? extends Enum>> map = new HashMap<>();\nmap.put("Animal", Animal.class);\nmap.put("Bird", Bird.class);\nfor (Enum value : map.get("Animal").getEnumConstants()) \n System.out.println(value.name());\n
" -> "java\nMap<String, Class<? extends Enum>> map = new HashMap<>();\nmap.put("Animal", Animal.class);\nmap.put("Bird", Bird.class);\nfor (Enum value : map.get("Animal").getEnumConstants()) \n System.out.println(value.name());\n
"
英文:
There doesn't appear to be an exact solution to what you're looking to achieve.
Essentially, I believe that since an enum is considered a static object, you cannot cast the static reference into a new object.
You would have to use a Class<Animal> type.
And, at that rate, you're better off just utilizing the Enum class.
Here is a tutorial on Java reflection with enums, for this specific requirement.
Examining Enums (The Java™ Tutorials > The Reflection API > Arrays and Enumerated Types).
Since you know that your map values are going to be enum objects, you can utilize the Enum#valueOf method, to obtain a single value.
If you want a list of values, similar to the values method, you can use an array of Enum and utilize the Class#getEnumConstants.
Map<String, Class<? extends Enum>> map = new HashMap<>();
map.put("Animal", Animal.class);
map.put("Bird", Bird.class);
for (Enum value : map.get("Animal").getEnumConstants())
System.out.println(value.name());
答案4
得分: -1
我通过Reflections找到了一个解决方案。可以这样做:
Map<String, Class<? extends Enum<?>>> errorCodes = errorCodeMap.getErrorCodeMap();
Class<? extends Enum<?>> enumClass = errorCodes.get(code.substring(0, 1));
Enum<?>[] enumConstants = enumClass.getEnumConstants();
Class<?> actualEnumClass = enumConstants[0].getDeclaringClass();
StringBuilder errorCode = new StringBuilder().append(prefix).append(code);
Enum<?> errorEnum = Enum.valueOf(actualEnumClass.asSubclass(Enum.class), errorCode.toString());
英文:
I found a solution through Reflections . It can be sone like this
Map<String, Class<? extends Enum<?>>> errorCodes = errorCodeMap.getErrorCodeMap();
Class<? extends Enum<?>> enumClass = errorCodes.get(code.substring(0, 1));
Enum<?>[] enumConstants = enumClass.getEnumConstants();
Class<?> actualEnumClass = enumConstants[0].getDeclaringClass();
StringBuilder errorCode = new StringBuilder().append(prefix).append(code);
Enum<?> errorEnum = Enum.valueOf(actualEnumClass.asSubclass(Enum.class), errorCode.toString());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论