Use a generic toString()Tag(s): Language
import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; public class ClassUtils { private ClassUtils() {} public static String toString( Object o ) { ArrayList<String> list = new ArrayList<String>(); ClassUtils.toString( o, o.getClass(), list ); return o.getClass().getName().concat( list.toString() ); } private static void toString( Object o, Class<?> clazz, List<String> list ) { Field f[] = clazz.getDeclaredFields(); AccessibleObject.setAccessible( f, true ); for ( int i = 0; i < f.length; i++ ) { try { list.add( f[i].getName() + "=" + f[i].get(o) ); } catch ( IllegalAccessException e ) { e.printStackTrace(); } } if ( clazz.getSuperclass().getSuperclass() != null ) { toString( o, clazz.getSuperclass(), list ); } } }
public class ClassUtilsTest { String hello = "world"; int i = 42; public static void main(String ... args) { System.out.println(ClassUtils.toString(new ClassUtilsTest())); // output : ClassUtilsTest[hello=world, i=42] } }
public class ClassUtilsTest2 extends ClassUtilsTest { String hello="fubar"; double d = Math.PI; public static void main(String ... args) { System.out.println(ClassUtils.toString(new ClassUtilsTest2())); // output : ClassUtilsTest2[hello=fubar, d=3.141592653589793, hello=world, i=42] } }
Andres Santana wrote :
I saw this article (use a generic toString()) and I might have another solution
for it using java.beans.Introspector.
/** * Print all properties for a given bean. It's useful for overwriting * toString method. * * @param bean * Object to get all properties from. * @param showNulls * Determine if you wether you want to show null properties or * not. * @return String representing bean state. * @author andres santana */ public static String showBean(Object bean, boolean showNulls) { if (bean == null) return null; StringBuilder sb = new StringBuilder(bean.getClass().getName()).append("["); try { BeanInfo bi = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] pd = bi.getPropertyDescriptors(); for (int i = 0; i < pd.length; i++) { if (!"class".equals(pd[i].getName())) { Object result = pd[i].getReadMethod().invoke(bean); if (showNulls || result != null) { sb.append(pd[i].getDisplayName()).append("=").append(result); if (i == pd.length - 1) continue; sb.append(","); } } } } catch (Exception ex) { } return sb.append("]").toString(); }