Constant to Field Name

Any given class may have some predefined Constant values. In java these are declared as public static final fields. One such example is Color. You can call something like Color.RED and use that to set your brush so that it is colored in red. But sometimes you will need the opposite direction. If you get the number 5 you may want to know which predefined color that is or you might be listening for KeyEvents and get the value 116 and you don’t want to guess which key your user just pressed. In my specific case I get a 6 as a result to BufferedImage.getType(). That does not tell me much. What I need is a human readable description of the image type.

One way is to compare this to all known fields of BufferedImage with a simple case  switch list (for my case only). This might even be faster but it is not a nice solution and everytime you do this you will need to create a specific solution for just that type of object. Through some internet research I came up with this more general solution :

public String constantToFieldName(Object obj, int constant) throws Exception {
    for (Field f : obj.getClass().getDeclaredFields()){
        int mod = f.getModifiers();
        if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && Modifier.isFinal(mod)) {
            if ( Integer.parseInt(f.get(null).toString()) == constant ){
                return f.getName();
            }
        }        
    }
    throw new Exception ("Could not find within given fields");
}

This solution uses a little bit of Java Reflection to get a list of all fields for the given object’s class and look in them for those that seem to be constant values. From these Values it is compared one-by-one. As I said this will not be a fast solution. Reflection alone will take it’s couple of microseconds. But for debuging my code without creating new lists everytime it is a pretty handy solution. For me this got a fixed part of my toolbox.

Of coursemy solution is also limited to integer fields only, but changing that to cover other types is easy. And also there is always the list of all known constant fields (for the java API at least) at :
http://docs.oracle.com/javase/7/docs/api/constant-values.html

One thought on “Constant to Field Name

  1. Seems I had to improve the code. I added the following line before the modifier checks:
    if (f.getType().isAssignableFrom(Integer.TYPE)){
    Since I am comparing integers it would make more sense to check first if the field is an integer at all. I wonder if it would perform better if I first do the modifier checks and then look for the correct type.

Comments are closed.