toString

public abstract class ToStringBasicVO {

    private static ObjectMapper objectMapper = new ObjectMapper();
    
    public String toString() {
        try {
            return objectMapper.writeValueAsString(this);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
 

方法二:

import java.lang.reflect.Field;
public class BaseBean {
  
    public String toString() {
       StringBuffer sb = new StringBuffer();
       try {
           Class t = this.getClass();
           Field[] fields = t.getDeclaredFields();
           for (int i = 0; i < fields.length; i++) {
              Field field = fields[i];
              field.setAccessible(true);
              sb.append("{");
              sb.append(field.getName());
              sb.append(":");
              if (field.getType() == Integer.class) {
                  sb.append(field.getInt(this));
              } else if (field.getType() == Long.class) {
                  sb.append(field.getLong(this));
              } else if (field.getType() == Boolean.class) {
                  sb.append(field.getBoolean(this));
              } else if (field.getType() == char.class) {
                  sb.append(field.getChar(this));
              } else if (field.getType() == Double.class) {
                  sb.append(field.getDouble(this));
              } else if (field.getType() == Float.class) {
                  sb.append(field.getFloat(this));
              } else
                  sb.append(field.get(this));
              sb.append("}");
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return sb.toString();
    }
}

 测试类

 

public class TestBean extends BaseBean {
    private int id;
    public int getId() {
       return id;
    }
    public void setId(int id) {
       this.id = id;
    }
    public static void main(String[] args) {
       TestBean testBean = new TestBean();
       testBean.setId(9);
       System.out.println(testBean.toString());
    }
}
 

你可能感兴趣的:(toString)