Pages

Java Reflection - Getting name of color without comparision

In this tutorial I am describing how get value of field/ property defined in class dynamically using Java Reflection.
And i am using it to get name of color (java.awt.Color) using Reflection.

Instead of doing lengthy comparison (shown below), we can do this easily by using java reflection:
   public static String getNameReflection(Color colorParam) {
        try {
            //first read all fields in array
            Field[] field = Class.forName("java.awt.Color").getDeclaredFields();
            for (Field f : field) {
                String colorName = f.getName();
                Class<?> t = f.getType();
                // System.out.println(f.getType());
                // check only for constants - "public static final Color"
                if (t == java.awt.Color.class) {
                    Color defined = (Color) f.get(null);
                    if (defined.equals(colorParam)) {
                        System.out.println(colorName);
                        return colorName.toUpperCase();
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Error... " + e.toString());
        }
        return "NO_MATCH";
    }

Getting name of color by Comparision
One solution to get name of color may be by comparison like this :
    public static String getNameByComparision(Color color) {
        if (color.equals(Color.RED)) {
            return "RED";
        }
        if (color.equals(Color.BLACK)) {
            return "BLACK";
        }
        // ..
        return "NOT_DEFINED";
    }

No comments:

Post a Comment

Your Comment and Question will help to make this blog better...