Dec 15, 2009

Generating Proper equals() and hashCode() by @Equiv Annotations

We've released a small Groovy library named "kobo-commons" which has some convenience features for Groovy programming.


@Equiv annotation is one of the features.

If you annotate fields by @Equiv annotations, you can dynamically generate
proper equals() and hashCode() using specified fields.


If you wrote the following groovy code:
  1. class Sample {  
  2.     @Equiv  
  3.     String name  
  4.   
  5.     @Equiv  
  6.     String value  
  7.   
  8.     String ignored  
  9. }  

then you could use equals method and hashCode method:
  1. def s1 = new Sample(name:'John', value:'Good', ignored:'Garbage')  
  2. def s2 = new Sample(name:'John', value:'Good', ignored:'Gold')  
  3. def s3 = new Sample(name:'John', value:'Bad',  ignored:'Garbage')  
  4. def s4 = new Sample(name:'Mike', value:'Good', ignored:'Garbage')  
  5.       
  6. assert s1 == s1  
  7. assert s1 == s2  
  8. assert s1 != s3  
  9. assert s1 != s4  
  10.       
  11. assert s1.hashCode() == s1.hashCode()  
  12. assert s1.hashCode() == s2.hashCode()  
  13. assert s1.hashCode() != s3.hashCode()  
  14. assert s1.hashCode() != s4.hashCode()  


I think it's useful for entities, etc. You can keep your classes very simple.

No comments:

Post a Comment