java 如何在Java中创建一个带有连字符的值的静态枚举?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2493002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:27:57  来源:igfitidea点击:

How to create a static enum with a value that has a hyphen symbol in Java?

javaenums

提问by coder

how to create the static enum like below

如何创建静态枚举如下

static enum Test{
    employee-id,
    employeeCode
}

As of now, I am getting errors.

到目前为止,我遇到了错误。

回答by Daniel Rikowski

This is not possible with Java, because each item has to be a valid identifier (and valid Java identifiers may not contain dashes).

这在 Java 中是不可能的,因为每个项目都必须是一个有效的标识符(并且有效的 Java 标识符可能不包含破折号)。

The closest thing would be adding a custom property to each enum value or override the toStringmethod, so you can do the following:

最接近的是为每个枚举值添加一个自定义属性或覆盖该toString方法,因此您可以执行以下操作:

Test.EMPLOYEE_ID.getRealName();    // Returns "employee-id"
Test.EMPLOYEE_CODE.getRealName();  // Returns "employeeCode"

public enum Test
    EMPLOYEE_ID("employee-id"),
    EMPLOYEE_CODE("employeeCode");

    private Test(String realName) {
        this.realName = realName;
    }
    public String getRealName() {
        return realName;
    }
    private final String realName;
}

回答by BalusC

This is not specific to enums. This applies to all identifiers in Java: class names, method names, variable names, etcetera. Hyphens are simply not allowed. You can find all valid characters in Java?Language?Specification, chapter 3.8 "Identifiers".

这不是特定于枚举的。这适用于 Java 中的所有标识符:类名、方法名、变量名等。连字符是不允许的。您可以在Java?Language?Specification,第 3.8 章“标识符”中找到所有有效字符。

To illustrate the problem:

为了说明问题:

int num-ber = 5;
int num = 4;
int ber = 3;

System.out.println(num-ber);

What would you expect to happen here?

你希望在这里发生什么?

回答by polygenelubricants

You can not do this. Enum constants must be legal Java identifiers. Legal Java identifiers can not contain -. You can use _if that's an acceptable substitute.

你不能做这个。枚举常量必须是合法的 Java 标识符。合法的 Java 标识符不能包含-. _如果这是可接受的替代品,您可以使用。

回答by Fazal

You cannot declare the enum constant with a hyphen. If you hyphen to be retrieved as the value of the enum, you should have a value method in enum which you either use in its toString method or access this method on the enum to get the hyphen value

您不能使用连字符声明枚举常量。如果您将连字符作为枚举的值进行检索,则您应该在 enum 中有一个 value 方法,您可以在其 toString 方法中使用该方法或在枚举上访问此方法以获取连字符值