जो मैं उपयोग करता हूं वह मुख्य रूप से हैशकोड() और बराबर() को लागू करने के लिए है। मैंने इकाई को सुंदर प्रिंट करने के लिए एक विधि भी जोड़ा। ऊपर डीआर के जवाब में, इनमें से अधिकतर ओवरराइड किया जा सकता है, लेकिन मेरे कार्यान्वयन में आप लंबे प्रकार के आईडी के साथ फंस गए हैं।
public abstract class BaseEntity implements Serializable {
public abstract Long getId();
public abstract void setId(Long id);
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
return result;
}
/**
* @see java.lang.Object#equals(Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BaseEntity other = (BaseEntity) obj;
if (getId() == null) {
if (other.getId() != null)
return false;
} else if (!getId().equals(other.getId()))
return false;
return true;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return new StringBuilder(getClass().getSimpleName()).append(":").append(getId()).toString();
}
/**
* Prints complete information by calling all public getters on the entity.
*/
public String print() {
final String EQUALS = "=";
final String DELIMITER = ", ";
final String ENTITY_FORMAT = "(id={0})";
StringBuffer sb = new StringBuffer("{");
PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(this);
PropertyDescriptor property = null;
int i = 0;
while (i < properties.length) {
property = properties[i];
sb.append(property.getName());
sb.append(EQUALS);
try {
Object value = PropertyUtils.getProperty(this, property.getName());
if (value instanceof BaseEntity) {
BaseEntity entityValue = (BaseEntity) value;
String objectValueString = MessageFormat.format(ENTITY_FORMAT, entityValue.getId());
sb.append(objectValueString);
} else {
sb.append(value);
}
} catch (IllegalAccessException e) {
// do nothing
} catch (InvocationTargetException e) {
// do nothing
} catch (NoSuchMethodException e) {
// do nothing
}
i++;
if (i < properties.length) {
sb.append(DELIMITER);
}
}
sb.append("}");
return sb.toString();
}
}
स्रोत
2009-01-05 23:45:20
मुझे माफ करना, लेकिन क्यों आप थोड़ी देर के पाश का उपयोग कर रहे हैं जो पाश के लिए एक में और अधिक फिट करने के लिए लगता है के लिए? –
हां, मैं कुछ ऐसा कर सकता था: (i = 0; i
यह प्रश्न कुछ समय से हुआ है, लेकिन फिर भी, उपरोक्त बराबर() विधि में एक बग है, जो प्रॉक्सी के साथ समस्याएं पैदा कर सकता है: getClass()! = Obj.getClass() के बजाय या तो उपयोग करने योग्य है() या! (obj exampleof BaseEntity) – javashlook