如何通过提供字符串来检索常量值



考虑这个类

package com.bluegrass.core;
public class Constants {
    public static final String AUTHOR="bossman";
    public static final String COMPANY="Bluegrass";
    //and many more constants below
}

我想创建一个这样的函数:

getConstantValue("AUTHOR") //this would return "bossman"

任何想法如何做到这一点?

您可以使用反射:

public static String getConstantValue(String name) {
    try {
        return (String) Constants.class.getDeclaredField(name).get(null);
    } catch (Exception e) {
        throw new IllegalArgumentException("Constant value not found: " + name, e);
    }
}

更新:枚举解决方案。

如果可以将Constants类更改为enum,它将是这样的:

private static String getConstantValue(String name) {
    return Constants.valueOf(name).getText();
}

但这需要这样的东西Constants

public enum Constants {
    AUTHOR("bossman"),
    COMPANY("Bluegrass");
    private final String text;
    private Constants(String text) {
        this.text = text;
    }
    public String getText() {
        return this.text;
    }
}

可能最简单的解决方案(并且也使用枚举而不是字符串是类型安全的(是使用枚举,前提是您能够将public static final字段更改为枚举。

public enum Constants {
    AUTHOR("bossman"),
    COMPANY("Bluegrass");
    private final String content;
    Constants (String content) {
        this.content= content;
    }
    public String getContent() {
        return content;
    }
    public static Constants getConstant(String content) {
        for (Constants constant : Constants.values()) {
            if (constant.getContent().equals(content)) {
                return constant;
            }
        }
        return null; //default value
    }
}

用法:

Constants.valueOf("AUTHOR") == Constants.AUTHOR
Constants.getConstant("bossman") == Constants.AUTHOR
Constants.AUTHOR.getContent() == "bossman"
因此,与其说是

OP的getConstantValue("AUTHOR")不如Constants.valueOf("AUTHOR").getContent()

有很多

方法可以解决这个问题。

一种方法是使用开关。

例:

public String foo(String key) throws AnException {
  switch (key) {
    case case1:
      return constString1;
    case case2:
      return constString2;
    case case3:
      return constString3;
      ...
     default:
      throws NotValidKeyException; //or something along these lines
    }
}

另一种方法是创建一个map<string,string>并用所需的键对填充它。

最新更新