Problem get the value of a field in the Reflection API

From: Richard (rvlasimsky_at_voneconsulting.com)
Date: 01/29/04


Date: 29 Jan 2004 14:31:16 -0800

I have written a static method that uses the Reflection API to scrape
all of the names of the instance variables in a class and their
corresponding values; and then returns a hashMap containing a
key/value pair of the name of the variable and its corresponding
value. My problem is getting the value of the field, and everything I
have seen on usenet and in the javadoc tells me I am doing the right
thing. I think I found a bug in the JDK, but thought I'd throw it out
there to see if I am doing something wrong.

When I use the reflect API, specifically Field.get(Object o), it
returns the name of the variable, not the value contained in the
variable.

Note: The object (params) that I am passing in contains only primitive
types (double, int, etc.). I am using Java(TM) 2 Runtime Environment,
Standard Edition (build 1.4.2_03-b02).

Here is the code

        public static HashMap toHash(Object params)
        {
                try
                {
                        HashMap desc = new HashMap();
                        Class c = params.getClass();
                        Field[] fields = c.getFields();
                        for (int i = 0; i < fields.length; i++)
                        {
                                String key = fields[i].getName(); //PROBLEM #1: field name is in
ALL CAPS
                                Object value = fields[i].get(params); //PROBLEM #2: returns the
name of the field, not it's value desc.put(key, value);
                        }
                        return desc;
                }
                catch (SecurityException e)
                {
                        MiscUtils.write("Unable to convert parameters to hash. " +
e.getMessage(), SystemInfo.ERROR_MESSAGE_TYPE);
                        e.printStackTrace();
                }
                catch (IllegalArgumentException e)
                {
                        MiscUtils.write("Unable to convert parameters to hash. " +
e.getMessage(), SystemInfo.ERROR_MESSAGE_TYPE);
                        e.printStackTrace();
                }
                catch (IllegalAccessException e)
                {
                        MiscUtils.write("Unable to convert parameters to hash. " +
e.getMessage(), SystemInfo.ERROR_MESSAGE_TYPE);
                        e.printStackTrace();
                }
                return null;
        }

Any ideas?