打印类中的所有变量值 [英] Printing all variables value from a class
本文介绍了打印类中的所有变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类,里面有一个类似这样的人的信息:
I have a class with information about a Person that looks something like this:
public class Contact {
private String name;
private String location;
private String address;
private String email;
private String phone;
private String fax;
public String toString() {
// Something here
}
// Getters and setters.
}
我希望 toString()
为所有变量返回 this.name +" - "+ this.locations + ...
.我试图使用反射来实现它,如这个问题 但我无法打印实例变量.
I want toString()
to return this.name +" - "+ this.locations + ...
for all variables. I was trying to implement it using reflection as shown from this question but I can't manage to print instance variables.
解决这个问题的正确方法是什么?
What is the correct way to solve this?
推荐答案
来自 实现toString:
public String toString() {
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append( this.getClass().getName() );
result.append( " Object {" );
result.append(newLine);
//determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(newLine);
}
result.append("}");
return result.toString();
}
这篇关于打印类中的所有变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文