Use a generic toString() : toString « Class « Java






Use a generic toString()

    

import java.lang.reflect.Field;

public class Main {
  public static void main(String args[]) {
    System.out.println(new MyClass().toString());

  }
}

class MyClass {
  String hello = "hi";

  int i = 0;

  public String toString() {
    StringBuilder sb = new StringBuilder();
    Class cls = getClass();
    Field[] f = cls.getDeclaredFields();

    for (int i = 0; i < f.length; i++) {
      f[i].setAccessible(true);
      try {
        sb.append(f[i].getName()+"="+ f[i].get(this)+"\n");
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    if (cls.getSuperclass().getSuperclass() != null) {
      sb.append("super:"+ super.toString()+"\n");
    }
    return cls.getName()+"\n" + sb.toString();
  }
}

   
    
    
    
  








Related examples in the same category

1.ShowToString -- demo program to show default toString methodsShowToString -- demo program to show default toString methods
2.ToString -- demo program to show a toString method
3.Demonstrate toString() without an overrideDemonstrate toString() without an override
4.To String DemoTo String Demo
5.Reflection based toString() utilities
6.Constructs pretty string representation of object value
7.Null Safe To String
8.toString(Object[] array)
9.Array To String
10.Gets the toString of an Object returning an empty string ("") if null input.
11.Gets the toString that would be produced by Object if a class did not override toString itself.