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






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








5.32.toString
5.32.1.Override toString() for Box class.
5.32.2.override the toString method in your classes
5.32.3.Use Reflection To build toString method
5.32.4.Reflection based toString() utilities
5.32.5.Use a generic toString()
5.32.6.Jakarta Commons toString Builder