Java 如何遍历类成员?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2466038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I iterate over class members?
提问by Alexandre H. Tremblay
I am using the Java version of the Google App Engine.
我正在使用 Google App Engine 的 Java 版本。
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?
我将如何编写函数 getObject?
采纳答案by Michael Myers
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 tutorialfor more.
有关更多信息,请参阅反射教程。