Java 打印类中的所有变量值

我有一堂课,其中包含有关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 + ...所有变量。我试图使用反射来实现它,如该问题所示,但我无法打印实例变量。

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

回答:

从实现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 打印类中的所有变量值 的全部内容, 来源链接: utcz.com/qa/433180.html

回到顶部