如何遍历类成员? [英] How do I iterate over class members?

查看:14
本文介绍了如何遍历类成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我将如何编写函数 getObject?

How would I write the function getObject?

推荐答案

是的,您确实需要反思.它会是这样的:

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

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

(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.

这篇关于如何遍历类成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆