我寫了一個工具類,當我輸入一個對象,直接打印對象裡面的屬性
public class JavaUtil {
public static void toString(Object object){
Class clazz = object.getClass();//獲得類對象
StringBuilder sb = new StringBuilder();
sb.append("成員變量:\n");
Field[] fields = clazz.getFields();
for (Field field:fields){
sb.append(field.toGenericString()+"\n");
}
System.out.println(sb.toString());
}
}
public class POJO {
private Integer id;
private String name;
public POJO() {
}
public POJO(Integer id, String name) {
this.setId(id);
this.setName(name);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
POJO pojo = new POJO();
pojo.setId(1);
pojo.setName("任冠宇");
JavaUtil.toString(pojo);
}
}
getFields()方法只能獲得public的屬性
如果非得獲取只能用getDeclaredMethods()方法,然後自己手動裁剪字符串了