Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 member variables of the object. Each object(s) 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
203 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

public static void 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));
    }
}

(As pointed out by ceving, the method should now be declared as void since it does not return anything, and as static since it does not use any instance variables or methods.)

See the reflection tutorial for more.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...