Macarse Macarse - 1 year ago 88
Java Question

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.

I want
to return +" - "+ 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?

Answer Source

From Implementing toString:

public String toString() {
  StringBuilder result = new StringBuilder();
  String newLine = System.getProperty("line.separator");

  result.append( this.getClass().getName() );
  result.append( " Object {" );

  //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 ) {

  return result.toString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download