gpt4 book ai didi

java - 打印类中的所有变量值

转载 作者:IT老高 更新时间:2023-10-28 13:53:50 25 4
gpt4 key购买 nike

我有一个类,其中包含有关 Person 的信息,如下所示:

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 + ...。我试图使用反射来实现它,如 this question 所示。但我无法打印实例变量。

解决这个问题的正确方法是什么?

最佳答案

来自 Implementing 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();
}

关于java - 打印类中的所有变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1526826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com