how to update Java constructors,equals,hash,etc. in eclipse?
I wanted to know if anyone knows about a good way to update,constructors, equals,hash,to string, etc. generated by eclipse in Java. Lot's of time, after I use the auto-generated code-stubs, I add a member variable to the class, and then I need to delete the auto-generated code, and do it all over again. Is there a way to cause eclipse to add the new variable to the auto-generated code-stubs ?
edit: ok deleting is not e开发者_高级运维ssential, however I still have to go and generate each on of them, I'm looking for an automatic solution.
This isn't exactly a solution to your question, but I no longer use the Eclipse auto-generated methods, I use the Apache commons lang EqualsBuilder and HashCodeBuilder:
So, for instance you can do:
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
public class EqualsTest {
private String foo;
private int bar;
// getters and setters
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
}
This uses reflection, and doesn't need changing when you add a field. However, there are other options where you can specify the fields to use, and if you want to take into account the hashCode of the superclass as well.
EDIT: As has been pointed out, the reflection aspect of this may have some performance penalties associated. Personally, I don't use the reflection HashCodeBuilder or EqualsBuilder in production code, I use the toHashCode (as below). I do however use the ReflectionToStringBuilder for logging and such like.
Here is an example which doesn't use reflection, but requires you to add another line when you add a field:
public int hashCode() {
// you pick a hard-coded, randomly chosen, non-zero, odd number
// ideally different for each class
return new HashCodeBuilder(17, 37).
append(foo).
append(bar).
toHashCode();
}
For more discussion about hashCodeBuilder, see apache commons equals/hashcode builder
Take a look at www.projectlombok.org as an alternative to writing these methods yourself. In particular the @Data annotation seems to fit your need, see http://www.projectlombok.org/features/Data.html.
Iv'e created a project of my own with one field and asked eclipse to generate all the base methods. After that I added a new field, I asked it to generate these methods again (source -> generate...), it prompted me about replacing the old ones, I clicked 'yes' and the updated methods were displayed.
Hope it helped
精彩评论