实体类自动重写toString(),equals()和hashCode()方法

时间:2021-07-16 16:14:27

编写web项目时会遇到大量的实体类,那么多的实体类都要重写toString(),equals()和hashCode()方法,造成大量重复代码。

解决方法:

1.编写一个抽象类,在类中重写以上三个方法。

2.让实体类继承这个抽象类。

所用jar包:

apache-commons-lang.jar

例子程序:

Model.java抽象类

package justest;

import java.io.Serializable;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

public abstract class Model implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;

public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}

public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}

public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
}

Student.java实体类

package justest;

public class Student extends Model {

private static final long serialVersionUID = 1L;

private Long id;
private String name;

public Student(Long id, String name) {
super();
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
}

AutoOverride3Method.java测试类

package justest;

public class AutoOverride3Method {
public static void main(String[] args) {
Student s1 = new Student(1L, "张三");
Student s2 = new Student(2L, "李四");
Student s3 = new Student(1L, "张三");

//测试toString()方法
System.out.println(s1);

//测试equals方法
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
}

}

输出:

Student[id=1,name=张三]
false
true