【发布时间】:2008-11-11 15:00:58
【问题描述】:
默认生成的 hashCode 和 equals 实现充其量是丑陋的。
是否有可能让 Eclipse 从 HashCodeBuilder 和 EqualsBuilder 生成一个,甚至可能使用 ToStringBuilder 生成一个 toString?
【问题讨论】:
默认生成的 hashCode 和 equals 实现充其量是丑陋的。
是否有可能让 Eclipse 从 HashCodeBuilder 和 EqualsBuilder 生成一个,甚至可能使用 ToStringBuilder 生成一个 toString?
【问题讨论】:
【讨论】:
您可以配置 Eclipse 以使用自定义构建器生成 toString()。在我们的例子中,ToStringBuilder 来自 Apache Commons Lang。你可以在这里看到http://azagorneanu.blogspot.com/2011/08/how-to-generate-equals-hashcode.html 怎么做。
该博文还包含使用 Apache Commons Lang 构建器生成 equals()、hashCode() 和 compareTo() 的 Eclipse 模板。
【讨论】:
您可以使用 Eclipse 中的代码模板来做到这一点。
这是我在 HashCodeBuilder 和 EqualsBuilder 示例中找到的 solution。
模板 EqualsBuilder:
public boolean equals(Object o) {
boolean result = false;
if (this == o) {
result = true;
} else if (o instanceof $CLASSNAME$) {
$CLASSNAME$ other = ($CLASSNAME$) o;
result = new org.apache.commons.lang.builder.EqualsBuilder()
.append($END$
.isEquals();
}
return result;
}
模板 HashCodeBuilder:
public int hashCode() {
return new org.apache.commons.lang.builder.HashCodeBuilder()
.append( $END$ )
.toHashCode();
}
【讨论】:
我使用名为“Commonclipse”的 Eclipse 插件
安装后,当您在 Java 源文件中单击鼠标右键时,您会看到一个新的上下文菜单项“commonclipse”。它可以基于Apache commons库生成equals、hashcode、toString和compareTo方法。
要安装它,请在 Eclipse 更新中使用它:http://commonclipse.sourceforge.net
【讨论】:
我制作了这个模板,检查了几个答案、网站并在 Eclipse Luna 上对其进行了测试。转到 Windows->Preferences,然后转到 Java->Editor->Templates 并将其添加到那里。
${:import(org.apache.commons.lang3.builder.HashCodeBuilder, org.apache.commons.lang3.builder.EqualsBuilder)}
@Override
public int hashCode() {
HashCodeBuilder hashCodeBuilder = new HashCodeBuilder();
hashCodeBuilder.append(${field1:field});
hashCodeBuilder.append(${field2:field});
hashCodeBuilder.append(${field3:field});
hashCodeBuilder.append(${field4:field});
hashCodeBuilder.append(${field5:field});
return hashCodeBuilder.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
${enclosing_type} rhs = (${enclosing_type}) obj;
EqualsBuilder equalsBuilder = new EqualsBuilder();
equalsBuilder.append(${field1}, rhs.${field1});
equalsBuilder.append(${field2}, rhs.${field2});
equalsBuilder.append(${field3}, rhs.${field3});
equalsBuilder.append(${field4}, rhs.${field4});
equalsBuilder.append(${field5}, rhs.${field5});${cursor}
return equalsBuilder.isEquals();
}
【讨论】:
eclipse 3.5.0 的 Eclipse java 代码模板,源自 Bruno Conde 的模板:
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (obj == this) {
return true;
} else if (obj.getClass() != this.getClass()) {
return false;
}
${enclosing_type} other = (${enclosing_type}) obj;
return new EqualsBuilder()//
.appendSuper(super.equals(other))//
.append(${cursor})//
.isEquals();
}
和
@Override
public int hashCode() {
return new HashCodeBuilder(${cursor})//
.append()//
.toHashCode();
}
【讨论】: