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

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

问题描述

我正在使用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?

解决方案

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

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

有关更多信息,请参见反射教程./p>

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?

解决方案

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.

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

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