views:

164

answers:

1

Hello, I am using the java version of the google app engine.

I would like to create a function that can receive as parameters many types of objects. I would like to print out the members of the object. Each objects may be different and the function must work for all objects. Do I have to use reflection - if so, what kind of code do I need to write?

public class dataOrganization {
  private String name;
  private String contact;
  private PostalAddress address;

  public dataOrganization(){}
}

public int getObject(Object obj){
  // This function prints out the name of every 
  // member of the object, the type and the value
  // In this example, it would print out "name - String - null", 
  // "contact - String - null" and "address - PostalAddress - null"
}

How would I write the function getObject?

+2  A: 

Yes, you do need reflection. It would go something like this:

public int getObject(Object obj) {
    for (Field field : obj.getClass().getDeclaredFields()) {
        //field.setAccessible(true); // if you want to modify private fields
        System.out.println(field.getName()
                 + " - " + field.getType()
                 + " - " + field.get(obj));
    }
}

See the reflection tutorial for more.

Michael Myers