简体   繁体   English

表示Java中的常量列表

[英]Represent a list of constants in java

I hope to manage static final String from "0" to "1" so that when I encounter a String counterpart, I can easily replace it with the constant. 我希望将static final String从“ 0”管理为“ 1”,以便在遇到String对应项时,可以轻松地用常量替换它。 Right now the best I can do is to declare all the constants at the beginning of the class: 现在,我能做的最好的就是在类的开头声明所有常量:

private static final String ZERO = "0";
private static final String ONE = "1";
private static final String TWO = "2";
...

But then for a String, I have to check the value of it (eg if it is one of "0" to "1") and then replace it with corresponding constant. 但是对于字符串,我必须检查它的值(例如,如果它是“ 0”到“ 1”之一),然后将其替换为相应的常量。 I'm wondering if there is a better way to handle this? 我想知道是否有更好的方法来解决这个问题?

This is used as an input of an API. 这用作API的输入。 The API requires String that is a compile time constant. API要求使用String作为编译时间常数。 For example if the string I obtained is "1" then I will input ONE (which is a constant string "1" ) to the API. 例如,如果我获得的字符串为“ 1”,那么我将向API输入ONE(这是常量字符串“ 1”)。

Yes there is, use enums. 是的,有,使用枚举。

public enum NumberValues { ONE, TWO, THREE, FOUR }  

for (Numbervalues num : NumberValues.values())  
    System.out.println(num);

Output: 输出:

ONE
TWO
THREE
FOUR

to get the value of the Enum use 获取Enum使用的值

System.out.println(num.ordinal());

for more detailed introspection please visit. 有关更多自省的信息,请访问。 https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

You can write an enum like this: 您可以这样编写一个enum

enum Constants{

    ONE("1"),
    TWO("2");

    private final String value;

    private Constants(String value){
        this.value = value;
    }

    public static Constants findByValue(String value){
        for(Constants constants : values()){
            if(constants.value.equals(value)){
                return constants;
            }
        }
        return null;
    }

    public String getValue() {
        return value;
    }
}

Once you encounter a string (let's say "1"), you can check whether any enum is defined for it (with findByValue method) and if the result is not null, you can replace the value, eg: 一旦遇到string (假设为“ 1”),就可以检查是否为它定义了任何枚举(使用findByValue方法),如果结果不为null,则可以替换该值,例如:

public static void main(String[] args) throws Exception{
    String s = "1";
    Constants constant = Constants.findByValue(s);
    if(null != constant){
        s = s.replaceAll(constant.getValue(), constant.name());
    }
    System.out.println(s);
}

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

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