在Java中访问常量字段值的字符串表示形式 [英] Accessing string representations of constant field values in java
问题描述
我使用的导入类的常量字段值设置为:
public static final int BLUE = 1;
public static final int GREEN = 2;
等。
有什么办法吗从int值获取常量字段值的字符串表示形式的方法?
即
P.S。给定值2,我想得到一个绿色的字符串。
P.S。这不是我的课程,所以我不能使用枚举
如果,您可以更改包含这些常量的类,最好使用 value()
方法将其设为枚举。
否则,我建议使用反射来构建 Map< Integer,String>
一次,然后仅进行地图查找:
Map< Integer,String> valueToStringMap = new HashMap<>();
for(Field field:Foo.class.getFields()){
int修饰符= field.getModifiers();
if(field.getType()== Integer.class&&& Modifier.isPublic(modifiers)
&& Modifier.isStatic(modifiers)){
valueToStringMap.put( (整数)field.get(null),field.getName());
}
}
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
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());
}
}
这篇关于在Java中访问常量字段值的字符串表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!