通过commons-lang.jar包实现一个javabean的equals,hashCode和toString三个方法,一般情况下,用手工直接实现这三个方法比较繁琐,
而采用common-lang.jar实现起来就比较容易了。下面即是其实现的具体代码:
1package per.jone;
2import java.util.Date;
3import org.apache.commons.lang.builder.EqualsBuilder;
4import org.apache.commons.lang.builder.HashCodeBuilder;
5import org.apache.commons.lang.builder.ToStringBuilder;
6public class MyBean {
7 private Date date;
8 private String str;
9 private int age;
10
11 public MyBean(Date date, String str, int age) {
12 super();
13 this.date = date;
14 this.str = str;
15 this.age = age;
16 }
17 public Date getDate() {
18 return date;
19 }
20 public void setDate(Date date) {
21 this.date = date;
22 }
23 public String getStr() {
24 return str;
25 }
26 public void setStr(String str) {
27 this.str = str;
28 }
29 public int getAge() {
30 return age;
31 }
32 public void setAge(int age) {
33 this.age = age;
34 }
35
36 @Override
37 public boolean equals(Object obj) {
38 if(obj==null){
39 return false;
40 }
41 if(obj==this){
42 return true;
43 }
44 if(obj.getClass()!=this.getClass()){
45 return false;
46 }
47 MyBean mb = (MyBean)obj;
48 return new EqualsBuilder().append(this.date, mb.getDate()).append(this.str, mb.getStr())
49 .append(this.age, mb.getAge()).isEquals();
50 }
51
52 @Override
53 public int hashCode() {
54 return new HashCodeBuilder(17,37).append(this.date).append(this.str).append(this.age).toHashCode();
55 //注意:HashCodeBuilder这个构造器的两个参数必须为奇数。
56 }
57
58 @Override
59 public String toString() {
60 return new ToStringBuilder(this).append("date",this.date).append("str",this.str).append("age",this.age).toString();
61 }
62}
我们可以看到依然需要手动维护这么多的属性,在common-lang.jar包里面还可通过反射机制来实现这三个方法,便于代码的维护,具体实现如下:
1@Override
2 public boolean equals(Object obj) {
3 return EqualsBuilder.reflectionEquals(this, obj);
4 }
5 @Override
6 public int hashCode() {
7 return HashCodeBuilder.reflectionHashCode(this);
8 }
9 @Override
10 public String toString() {
11 return ToStringBuilder.reflectionToString(this);
12 }