bean通过反射重写toString

思路1:

网上一大把,通过this.getClass().getDeclaredFields();获得所有属性,禁掉访问限制,最终输出属性值

// public String toString2() {
// System.out.println("enter sourceObj toString...");
//
// StringBuffer sb = new StringBuffer();
// Field[] fields = this.getClass().getDeclaredFields();
// for(Field iField : fields) {
// iField.setAccessible(true);
// sb.append(iField.getName());
// sb.append("=");
// try {
// sb.append(iField.get(this));
// }catch(IllegalArgumentException e) {
// e.printStackTrace();
// }catch(IllegalAccessException e) {
// e.printStackTrace();
// }
// sb.append("\n");
// }
// return sb.toString();
//
}

思路2:
bean自身有public的get set方法,找到对应方法,截取名字,通过Method.invoke方法得到当前属性值
public  String toString(){
System.out.println("SourceObj toString1...");

Class<?> clazz = this.getClass();
StringBuffer res = new StringBuffer(clazz.getSuperclass().getName() + " \n");
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
// System.out.println(clazz.getName());
Method[] methods = clazz.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method tmp = methods[i];
String mName = tmp.getName();
if (mName.startsWith("get")) {
String fName = mName.substring(3);
res.append(fName + " = ");
try {
Object o = tmp.invoke(this, null);
if (o == null) {
res.append(" null \n");
continue;
}
if (o instanceof Double) {
res.append("" + ((Double) o).doubleValue() + " \n");
} else if (o instanceof Float) {
res.append("" + ((Float) o).floatValue() + " \n");
} else if (o instanceof Long) {
res.append("" + ((Long) o).longValue() + " \n");
} else if (o instanceof String) {
res.append("" + (String) o + " \n");
} else if (o instanceof Date) {
res.append("" + ((Date) o).toString() + " \n");
} else {
res.append("" + o.toString() + " \n");
}
} catch (IllegalAccessException e) {
continue;
} catch (InvocationTargetException ex) {
continue;
}
}
}
}
return res.toString();
}

由于调用关系,需要注意getClass()获得的对象,this初始指向并不是bean本身。

bean:

 
public class SourceObj extends BaseObj{

private String context;
private String memo;
private String source;

public String getContext() { return context; }
public void setContext(String context) { this.context = context; }
public String getMemo() { return memo; }
public void setMemo(String memo) { this.memo = memo; }
public String getSource() { return source; }
public void setSource(String source) { this.source = source; }

public String toString(){...}
}
 

猜你喜欢

转载自www.cnblogs.com/redqueen/p/12512610.html
今日推荐