简体   繁体   English

通过枚举的构造函数值获取枚举

[英]Getting the enum by enum's constructor value

What is the right way of getting the enum by it's constructor value in java?通过java中的构造函数值获取枚举的正确方法是什么? Here's an example:下面是一个例子:

public enum Status{
CREATED("created"), IN_PROGRESS("inProgress"), COMPLETED("completed");

public final String statusStr;
Status(String statusStr){
  this.statusStr = statusStr;
}
}

So if the input I get is a string of 'created' how do I get Status.CREATED from it?因此,如果我得到的输入是一串“已创建”,我如何从中获取 Status.CREATED?

I don't think you can do it automatically.我不认为你可以自动做到这一点。 You will have to create a static method for that:您必须为此创建一个静态方法:

public static Status fromString(String string) {
    for (Status status : values()) {
        if (status.statusStr.equals(string)) {
            return status;
        }
    }
    throw new IllegalArgumentException(string);
}

Incorporating @Pshemo's suggestions, the code could also be:结合@Pshemo 的建议,代码也可以是:

@RequiredArgsConstructor @Getter
public enum Status {
    CREATED("created"), IN_PROGRESS("inProgress"), COMPLETED("completed");

    private static final Map<String, Status> MAP = Arrays.stream(Status.values())
            .collect(Collectors.toMap(Status::getStatusStr, Function.identity()));

    private final String statusStr;

    public static Status fromString(String string) {
        return Objects.requireNonNull(MAP.get(string));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM