Reflection based toString() utilities : toString « Class Definition « Java Tutorial






import java.lang.reflect.Field;

public class Main {
  String hello = "world";

  int i = 42;

  public static void main(String args[]) {
    System.out.println(Util.toString(new MyClass()));
    
    System.out.println(Util.toString(new MyAnotherClass()));
  }
}

class Util {
  public static String toString(Object o) {
    StringBuilder sb = new StringBuilder();
    toString(o, o.getClass(), sb);
    return o.getClass().getName()+ "\n"+sb.toString();
  }

  private static void toString(Object o, Class clazz, StringBuilder sb) {
    Field f[] = clazz.getDeclaredFields();

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

class MyClass {
  int i = 1;

  private double d = 3.14;
}

class MyAnotherClass extends MyClass{
  int f = 9;
}








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