Skip to content

Instantly share code, notes, and snippets.

@netstart
Created July 15, 2015 16:52
Show Gist options
  • Save netstart/26e1485ef3d17caad347 to your computer and use it in GitHub Desktop.
Save netstart/26e1485ef3d17caad347 to your computer and use it in GitHub Desktop.
default implementation to hashCode, equals and toString
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
public abstract class EntityBase implements EntityDef {
private static final long serialVersionUID = -4629136366635323935L;
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, getExcludeAsList());
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) {
return false;
}
if (obj == this) {
return true;
}
return EqualsBuilder.reflectionEquals(this, obj, getExcludeAsList());
}
@Override
public String toString() {
final ReflectionToStringBuilder toString = new ReflectionToStringBuilder(this);
toString.setAppendStatics(false);
toString.setAppendTransients(false);
toString.setExcludeFieldNames(getExcludeFieldsAsArray());
return toString.toString();
}
/**
* Sobrescreva este método caso queira excluir algum atributo, desconsiderando-os do hasCode, equals e toString
*
* String [] s = new String[] {"parentString", "parentInt", "ignoreString"}; Arrays.asList(s); return s;
*/
public String[] getExcludeFieldsAsArray() {
return new String[] {};
}
public List<String> getExcludeAsList() {
return Arrays.asList(getExcludeFieldsAsArray());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment