Getting All Field Names and their corresponding values using Java Reflection


Hi All,

Today I am posting a simple source code to get all field names and their corresponding valuea present in a java class. Here I am using a simple java Reflection concept. Using java reflection we can access even private fields and can modify their vales. For more details on this you can refer to : http://java.sun.com/developer/technicalArticles/ALT/Reflection/

Hope you enjoy this code………….. 🙂

/**
 * All the code given is GPL v3 licensed. You can redistrubute it and can modify without any waranty.
 * © 2011 Narendra Kadali narendra_kadali@hotmail.com
 */
package util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import util.test.vo.User;

/**
 * @author <a href="mailto:narendra_kadali@hotmail.com">Narendra</a>
 *
 *
 * @version
 * @since Aug 27, 2011 5:21:49 AM
 */
public class ObjUtil
{
   private final static Logger logger = Logger.getLogger(ObjUtil.class);

   /**
    *
    * @param valueObj
    * @return
    * @since Aug 27, 2011 5:27:19 AM
    * @author Narendra
    * @throws IllegalAccessException
    * @throws IllegalArgumentException
    */
   public static Map getFieldNamesAndValues(final Object valueObj) throws IllegalArgumentException,
            IllegalAccessException
   {
      logger.info("Begin - getFieldNamesAndValues");
      Class c1 = valueObj.getClass();
      logger.info("Class name got is:: " + c1.getName());

      Map fieldMap = new HashMap();
      Field[] valueObjFields = c1.getDeclaredFields();

      // compare values now
      for (int i = 0; i &lt; valueObjFields.length; i++)
      {

         String fieldName = valueObjFields[i].getName();

         logger.info("Getting Field Values for Field:: " + valueObjFields[i].getName());
         valueObjFields[i].setAccessible(true);

         Object newObj = valueObjFields[i].get(valueObj);

         logger.info("Value of field" + fieldName + "newObj:: " + newObj);
         fieldMap.put(fieldName, newObj);

      }
      logger.info("End - getFieldNamesAndValues");
      return fieldMap;
   }

   public static void main(String args[])
   {
      User userObj = new User();
      try
      {
         System.out.println(getFieldNamesAndValues(userObj ));
      }
      catch (IllegalArgumentException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      catch (IllegalAccessException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
}
Advertisements

, ,

  1. #1 by Odilio Noronha Filho on August 31, 2011 - 8:35 PM

    Getting All Field Names and their corresponding values using Mirror

    http://projetos.vidageek.net/mirror/mirror/

    private String geraResposta(Object allPersons ){

    Object target = allPersons;

    Class clazz = allPersons.getClass() ;
    List l = new Mirror().on(clazz).reflectAll().fields();
    for (int i = 0; i < l.size()-1; i++) {
    Object value = new Mirror().on(target).get().field(l.get(i).getName());
    atualizacao.append(l.get(i).getName() +"="+ value+";");
    }

    return atualizacao.toString();
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: