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

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.



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 ");


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

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



ans.append(" of type ");



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


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();

// 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