java enum 通过key 获取值
时间: 2023-10-08 09:14:27
浏览: 74
可以通过以下[方式](https://geek.csdn.net/educolumn/0a7fca90472e8d39fd3078246e0b14f3?spm=1055.2569.3001.10083)获取 Java 的枚举类型中指定 key 对应的值:
```java
public enum ExampleEnum {
KEY1("value1"),
KEY2("value2"),
KEY3("value3");
private final [string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) value;
ExampleEnum([string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) value) {
this.value = value;
public [string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) getValue() {
return value;
public static ExampleEnum getByKey([string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) key) {
for (ExampleEnum e : ExampleEnum.values()) {
if (e.name().equals(key)) {
return e;
return null;
其中,`getByKey` 方法可以通过传入 key 值返回对应的枚举类型实例。例如:
```java
ExampleEnum exampleEnum = ExampleEnum.getByKey("KEY1");
System.out.println(exampleEnum.getValue()); // 输出 "value1"
```
相关问题
java Enum根据key值获取对应的value
在Java中,可以通过以下方式获取Enum类型的值:
1. 使用Enum的valueOf()方法,该方法根据传入的字符串参数返回对应的枚举常量,如果该字符串不是有效的枚举常量名称,则会抛出IllegalArgumentException异常。
public enum Color {
RED("红色"), GREEN("绿色"), BLUE("蓝色");
private String name;
Color(String name) {
this.name = name;
public String getName() {
return name;
Color color = Color.valueOf("RED");
System.out.println(color.getName()); // 输出:红色
```