小编典典

Java 打印类中的所有变量值

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

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


阅读 1220

收藏
2020-03-16

共1个答案

小编典典

从实现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();
}
2020-03-16