你可以使用eclipse的重构工具方便的生成javabean的getter和setter方法,但在编写javabean时,你可能不得不手动编写枯燥单调的继承自Object的隐含的常用方法,如toString(),hashcode(),equals(Object),compareTo(Object)。当然也有省力的解决方法,那就是eclipse的插件Commonclipse。Commonclipse使用commons-lang包,自动生成上面的方法。你可以到其网站
Commonclipse上下载插件感受一下。下面给出来自于Commonclipse网站的截图:
下面的代码是我写的一个简单的javabean及使用Commonclipse生成的代码:
package domain;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
public class User implements Comparable {
private String name;
private String pwd;
private long year;
private boolean sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public long getYear() {
return year;
}
public void setYear(long year) {
this.year = year;
}
/** *//**
* @see java.lang.Object#toString()
*/
public String toString() {
return new ToStringBuilder(this).append("sex", this.sex).append("name",
this.name).append("pwd", this.pwd).append("year", this.year)
.toString();
}
/** *//**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return new HashCodeBuilder(-1913143291, 1282699537).appendSuper(
super.hashCode()).append(this.sex).append(this.pwd).append(
this.name).append(this.year).toHashCode();
}
/** *//**
* @see java.lang.Comparable#compareTo(Object)
*/
public int compareTo(Object object) {
User myClass = (User) object;
return new CompareToBuilder().append(this.sex, myClass.sex).append(
this.pwd, myClass.pwd).append(this.name, myClass.name).append(
this.year, myClass.year).toComparison();
}
/** *//**
* @see java.lang.Object#equals(Object)
*/
public boolean equals(Object object) {
if (!(object instanceof User)) {
return false;
}
User rhs = (User) object;
return new EqualsBuilder().appendSuper(super.equals(object)).append(
this.sex, rhs.sex).append(this.pwd, rhs.pwd).append(this.name,
rhs.name).append(this.year, rhs.year).isEquals();
}
}