简体   繁体   English

Java 枚举插入值

[英]Java enums insert values

I have an enum created as below我创建了一个枚举,如下所示

public enum CustomData {

    SHOW_VAL("","");

    private final String valCode;
    private final String valD;  

    CustomData(String valCode, String valD){
        this.valCode = valCode;
        this.valD = valD;
    }

    public String getvalCode() {
        return this.valCode;
    }

    public String getvalD() {
        return this.valD;
    }   
}

I am throwing exception using the enum Custom Data.我正在使用枚举自定义数据抛出异常。 Right now, I can create multiple static types like SHOW_VAL("TEXT","DESC") , but I want to put the text in it at runtime when any error occurs.现在,我可以创建多个静态类型,如SHOW_VAL("TEXT","DESC") ,但我想在发生任何错误时在运行时将文本放入其中。

In the above, code how can I insert the values via the constructor defined above in other class?在上面的代码中,如何通过上面在其他类中定义的构造函数插入值?

Enums are a compile time constant, you can't create new ones in the runtime using regular language features.枚举是编译时常量,您不能使用常规语言功能在运行时创建新的。 As per Enum Type docs:根据 枚举类型文档:

You should use enum types any time you need to represent a fixed set of constants.任何时候需要表示一组固定的常量时,都应该使用枚举类型。 That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.这包括自然枚举类型,例如我们太阳系中的行星和数据集,其中您在编译时知道所有可能的值——例如,菜单上的选择、命令行标志等。

Use a regular class for runtime values.对运行时值使用常规class

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

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