一.定义抽象类,重写toString()方法
???? 在toString()方法中调commons-lang.jar的ToStringBuilder类的reflectionToString方法。这样,在日志输出时直接输出业务DTO对象,就能输出对象的属性及属性值。
class="java">package com.bijian.study; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; public abstract class AbstractDTO implements java.io.Serializable { private static final long serialVersionUID = 639200629041717L; public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } }
?
二.定义业务DTO对象,重写hashCode()、equals()方法,并实现Comparable接口
package com.bijian.study; public class PersonDTO extends AbstractDTO implements Comparable { //编码 private String code; //姓名 private String name; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((code == null) ? 0 : code.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof PersonDTO)) { return false; } PersonDTO other = (PersonDTO) obj; if (code == null) { if (other.code != null) { return false; } } else if (!code.equals(other.code)) { return false; } return true; } public int compareTo(Object object) { String thisCode = this.getCode(); String anotherCode = ((PersonDTO) object).getCode(); return thisCode.compareTo(anotherCode); } public static void main(String[] args) { PersonDTO personDTO = new PersonDTO(); personDTO.setCode("123"); personDTO.setName("Test"); System.out.println(personDTO); } }
?运行PersonDTO类的main方法,打印结果如下所示:
com.bijian.study.PersonDTO@173a10f[ code=123 name=Test ]? 这里其实就是调用commons-lang.jar的ToStringBuilder类的reflectionToString方法输出的格式样子,比较清蜥。