Java genralized toString() method

The contents of the toString() method can be used in any Java bean class. It uses reflection to get the values of all the available properties.

public String toString()
{
        Object obj = this;
        StringBuilder sb = new StringBuilder();
        Class clazz = obj.getClass();
        java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
               
        for (int i = 0; i < fields.length; i++)
        {
                java.lang.reflect.Field f = fields[i];

                try
                {
                        sb.append(f.getName() + " -> " + f.get(obj)+"\n");
                }
                catch (IllegalArgumentException e)
                {
                        e.printStackTrace();
                }
                catch (IllegalAccessException e)
                {
                        e.printStackTrace();
                }
        }
        return sb.toString();
}

Search