Link to home
Start Free TrialLog in
Avatar of eugeneng
eugeneng

asked on

how to use getInt(), getChar()... of reflect class?

I've the following class, can someone show me how to retrieve the value of each member variable by using reflect class?


class MyObject extends Object
{
   public String m_string;
   public int m_int;
   public char m_char;
   public byte m_byte;
   public bool m_bool;

   MyObject()
   {  
       m_string = new String("MyObject->m_String");
       m_int =  1000;
       m_char = 'A';
       m_byte = 10;
       m_bool = false;
   }
   public void printInfo()
   {
      Class c = getClass();
      Field[] fields = c.getFields();
      System.out.println("Class Name:" + c.getName());

      String type;
      String fname;
      for (i=0;i<fields.length;i++)
      {
     type = fields[i].getType().toString();
        fname = fields[i].getName();
        System.out.println("field.name:"  + fieldname);
        System.out.println("field.toString():"+fields[i].toString());
        System.out.println("field.type"  + type);
         :
         : then how to get the value of each field ?
       

      }

public static void main(String argc[])
{
    MyObject obj = new MyObject();
    obj.printInfo();
}


so my question is how to use reflect class to get the value of member variables of a object ?
Avatar of Andrew Crofts
Andrew Crofts
Flag of Ukraine image

Listening
ASKER CERTIFIED SOLUTION
Avatar of imladris
imladris
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
imladris is correct. Field.get returns an Object representing the value of the Field. Primitives are wrapped in an appropriate subclass of Number. As your posted code shows, you can get a printable representation simply by calling toString on the returned Object. Anything more substantial than this requires that you determine some more specific subclass then cast the object and operate on it as the subclass. For example:

    Object value = field[i].get(target);
    if (value instanceof Long) {
        long x = ((Long)value).longValue();
        // do something
    } else if (value instanceof Double) {
        double x = ((Double)value).doubleValue();
        // do something
    } else if (value instance of Vector) {
        Iterator iter = ((Vector)value).iterator();
        // do something
    } else if ( ... )

Normally you would also have to be concerned that Field.get could return null if the field is an object reference. Since all the fields in your examples are primitives this might not be a concern for you.

Jim
Avatar of eugeneng
eugeneng

ASKER

great!!, it works!!!, thanx man, thanx to you too jim_cakalic,