简体   繁体   English

Java中的Enum中为null

[英]null in Enum in Java

I have 3 enum types for a functionality in my controller. 我在控制器中有3种枚举类型用于功能。 Also, have set proper checks on UI. 另外,对UI进行适当的检查。 BUT, if someone tests the API with a value equal to null then I don't know how to handle that. 但是,如果有人用等于null的值测试API,那么我不知道该如何处理。

Here's the code: 这是代码:

public enum AuthStatus implements Comparable<AuthStatus> {
    ABC("test", "testtt", -1), 
    DEF("tesds", "dsds", 0), 
    .
    .

If ABC or DEF in given in the payload, everything works fine, what to do if nothing is given in payload,ie "". 如果有效负载中指定了ABC或DEF,则一切正常,如果有效负载中未指定任何内容,该怎么办,即“”。

Basically, I want to add "" as an enum type, eg: 基本上,我想添加“”作为枚举类型,例如:

ABC("test", "testtt", 2), 
DEF("tesds", "dsds", 0), 
""("invalid", "Not Valid", -1) // What should be replaced by "".

Enum names have to be valid Java identifiers, and there is no valid Java identifier that has zero characters length. 枚举名称必须是有效的Java标识符,并且没有有效的Java标识符,其字符长度为零。

If you want to match input against some value, then using a Java enum name to express that is not a good idea, as there are many more limitation to Java identifiers (can't contain spaces nor many other characters). 如果要将输入与某个值进行匹配,则使用Java枚举名称来表示它不是一个好主意,因为Java标识符有很多限制(不能包含空格或许多其他字符)。 You should add another field to your enum, you could call it matchValue , and match your input against that value rather than against the enum name. 您应该在枚举中添加另一个字段,可以将其命名为matchValue ,并将输入值与该值而不是枚举名称进行匹配。

public enum AuthStatus implements Comparable<AuthStatus> {
    ABC("ABC", "test", "testtt", -1), 
    INVALID("", "invalid", "Not Valid", -1);

    private final String matchValue;

    private AuthStatus(String matchValue, ...) {
        this.matchValue = matchValue;
    }
}

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

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