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






Reflection based toString() utilities

     

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

   
    
    
    
    
  








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.Use a generic toString()
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.