Not sure how to phrase that but I have this:
In a
public class DefinedValues{
public static final int CommandGroupLength = 0x00000001;
}
I want a way of getting the String "CommandGroupLength" from value 0x00000001;
Is that possible?
Not sure how to phrase that but I have this:
In a
public class DefinedValues{
public static final int CommandGroupLength = 0x00000001;
}
I want a way of getting the String "CommandGroupLength" from value 0x00000001;
Is that possible?
do you want to access the name of the variable that has the value 0x00000001? than this is not possible:
public class DefinedValues {
public static final int CommandGroupLength = 0x00000001;
}
with Java8 it is technically possible to at least get the name of a variable via reflection, see Java Reflection: How to get the name of a variable?
you can achieve the same thing much easier with a Map, which contains Key-Value-Pairs.
Map<String,Integer> myMap= new HashMap<>();
myMap.put("CommandGroupLength", 0x00000001);
then you write a function which searches in the entrySet of the Map for all keys that have that value, since it is not ensured there is only one, it'll need to return a Collection or Array or something similar. here's my code:
public static void main(String[] args) {
Map<String,Integer> myMap = new HashMap<>();
myMap.put("CommandGroupLength", 0x00000001);
myMap.put("testA", 5);
myMap.put("testB", 12);
myMap.put("testC", 42);
System.out.println("Searching for value 0x00000001 in myMap");
Set<String> searchResults = findKeyByValue(myMap, 0x00000001);
System.out.println("I found the following keys:");
boolean isFirst = true;
for(String result : searchResults) {
if(isFirst)
isFirst = false;
else
System.out.printf(", ");
System.out.printf("%s", result);
}
}
public static Set<String> findKeyByValue(Map<String, Integer> map, Integer value) {
Set<String> result = new HashSet<>();
if(value != null) {
Set<Entry<String, Integer>> entrySet = map.entrySet();
for(Entry<String, Integer> entry : entrySet) {
if(value.equals(entry.getValue())) {
result.add(entry.getKey());
}
}
}
return result;
}