【问题标题】:How do I iterate over class members?如何迭代类成员?
【发布时间】:2010-03-17 21:28:03
【问题描述】:

我使用的是 Java 版本的 Google App Engine。

我想创建一个可以接收多种类型对象作为参数的函数。我想打印出对象的成员变量。每个对象可能不同,并且该功能必须适用于所有对象。我必须使用反射吗?如果是这样,我需要编写什么样的代码?

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"
}

我将如何编写函数 getObject?

【问题讨论】:

标签: java reflection


【解决方案1】:

是的,你确实需要反思。它会是这样的:

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

(正如ceving 所指出的,该方法现在应该声明为void,因为它不返回任何内容,并且声明为static,因为它不使用任何实例变量或方法。)

请参阅reflection tutorial 了解更多信息。

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 2011-05-26
    • 2019-01-16
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多