Using java.lang.reflect to print all fields of an object
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   David_Howie
Posted On:   Wednesday, October 16, 2002 05:50 PM

I'd like to implement reflection to obtain all the fields of an object and print the field name and field value in the toString() method of the object. I know how to get the fields, but I don't understand how to use the getter methods for getting the field value.


Any help would be appreciated.


Thanks

Dave

Re: Using java.lang.reflect to print all fields of an object

Posted By:   Frederic_Fondement  
Posted On:   Friday, October 18, 2002 12:45 AM

Note: this will work for any object of any class.



public String toString () {

try {

StringBuffer ans = new StringBuffer();

Class clazz = this.getClass();

ans.append("Object of class ");

ans.append(clazz.getName());

java.lang.reflect.Field [] fields = clazz.getFields();

for (int i = 0; i < fields.length; ++i) {

ans.append('
');

ans.append(fields[i].getName());

ans.append(" of type ");

ans.append(fields[i].getType().getName());

ans.append(':');

//Field.getObject(this) returns an object representing the value for this object

ans.append(field[i].getObject(this).toString());

}
return ans.toString();
} catch (RuntimeException x) {

throw x;
} catch (Exception x) {

/*In case of IllegalArgumentException (that should not happen because this is always of class type this.getClass()) or IllegalAccessException (that should not happen because Class.getFields() returns only public fields)*/

throw new RuntimeException(x.toString());
}
}

Re: Using java.lang.reflect to print all fields of an object

Posted By:   Lasse_Koskela  
Posted On:   Wednesday, October 16, 2002 10:48 PM

What I understood from the API documentation was this:

// the object of which field values you want to get
MyObject myObj = new MyObject();
myObj.setNumber(123);
myObj.setText("abc");

// get Field objects for the member variables
Field field1 = getFieldSomehow(myObj, "number");
Field field2 = getFieldSomehow(myObj, "text");

// get the values of the Fields
Integer number = (Integer) field1.get(myObj);
String text = (String) field2.get(myObj);
About | Sitemap | Contact