How to customize hashCode() and equals() generated by Eclipse?

会有一股神秘感。 提交于 2019-11-29 06:16:40

问题


It is recommended and sometimes necessary, classes that represent values (value classes) to override hashCode(), equals() [and optionally toString()] methods. The values that these methods return depend on all or subset of the member variables of the class and its super-class. To implement them properly you have to know a little bit of theory about hashing and a little bit of algebra and set theory (not too much, and almost everything is explaind in the javadocs for these methods and in Effective Java form Josh Bloch.)
In most of the cases, the implementation of this methods follow a template, and IDEs (like Eclipse JDT) include tools to generate them. However, the tool generators, can not make any assumptions, and generate these methods using only constructs available in the language and the standard library. Because of that these methods usually look very ugly.

Another way to implement these methods is to use library like Apache's (commons-lang) HashCodeBuilder, EqualsBuilder and ToStringBuilder. Using these utilities, one can implement their own hashCode() and equals() methods that look much better.

My question is about combining these two approaches. I would like to be able to customize Eclipse's hashCode() and equals() generators, so that will generate them using HashCodeBuilder and friends. Is it possible (and how) to do this without tweaking the JDT? Only writing small plugin that will override the default implementations (but without changing JDT code).

Thanks.


回答1:


Posting my comment as an answer by request: Commonclipse, an Eclipse plugin that facilitates the use of Apache Commons, does what you want to do.

Caveat: I have no recent experience with this plugin, which is why I originally posted as a comment, and not as an answer.




回答2:


In the eclipse preferences (Window>Preferences) go to Java > Editor > Templates.

In there you can create a teplate with name:hashcode context:java description:Create a hashcode method. The Pattern should contain something like this:

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

Save and return to your java class. Type the name (hashcode) and press ctrl enter. You can then select your template from the drop down list.

Do the same for each method you want. You could also create a template that combines everything together as well.



来源:https://stackoverflow.com/questions/6255210/how-to-customize-hashcode-and-equals-generated-by-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!