【java】重写toString方法,用反射
1 /** 2 * 重写对象的toString方法 3 * 4 * @param object 5 * @return 6 */ 7 public static String objToString(Object object) { 8 if (null == object) { 9 return ""; 10 } 11 StringBuilder sb = new StringBuilder(object.getClass().getName()); 12 sb.append("{"); 13 Field[] fields = object.getClass().getDeclaredFields(); 14 Object obj; 15 boolean isOne = true; 16 for (Field field: fields) { 17 field.setAccessible(true); 18 try { 19 obj = field.get(object); 20 if (null != obj) { 21 if (isOne) { 22 isOne = false; 23 } else { 24 sb.append(", "); 25 } 26 sb.append(field.getName()).append("=").append(obj); 27 } 28 } catch (IllegalAccessException e) { 29 } 30 } 31 sb.append("}"); 32 return sb.toString(); 33 }
实体类调用
@Override public String toString() { return objToString(this); }
打印出来,如:
com.xiaostudy.Mytest{serialVersionUID=1, id=ididididididid, name=oooooooooooooooooo}