Printing all variables value from a class

java, reflection

Solution

From 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();
}

Problem

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. } ``` 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?

Original source

Related problems