Accessing string representations of constant field values in java

爷,独闯天下 提交于 2019-12-13 09:23:59

问题


I am using an imported class with has constant field values set using:

public static final int BLUE = 1;
public static final int GREEN = 2;

etc.

Is there any way of getting a string representation of the constant field value from the int value?

i.e. given the value 2 I want to get a string of GREEN.

P.S. This isn't my class so I can't use ENUMs


回答1:


If you can change the class which contains these constants, it would be better to make it an enum with a value() method.

Otherwise, I would suggest building a Map<Integer, String> once using reflection, and then just doing map lookups:

Map<Integer, String> valueToStringMap = new HashMap<>();
for (Field field : Foo.class.getFields()) {
    int modifiers = field.getModifiers();
    if (field.getType() == Integer.class && Modifier.isPublic(modifiers)
        && Modifier.isStatic(modifiers)) {
        valueToStringMap.put((Integer) field.get(null), field.getName());
    }
}



回答2:


I think your friend here would be enums

public enum Color {
  BLUE(1), GREEN(2);
}

Now if you try to get Color.BLUE.ordinalValue() it will return 1 and if you say Color.BLUE.name() it will return BLUE.

You can also declare private variables in the enum just like a pojo class and initialize them un the constructor. You can write getter methods to return those variables.



来源:https://stackoverflow.com/questions/22219181/accessing-string-representations-of-constant-field-values-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!