title: Java: clean way to automatically throw UnsupportedOperationException when calling hashCode() and equals()?
body: <p>We've got an OO codebase where in quite a lot of cases <code>hashcode()</code> and <code>equals()</code> simply don't work, mostly for the following reason:</p>
  
  <blockquote>
    <p>There is no way to extend an
    instantiable class and add a value
    component while preserving the equals
    contract, unless you are willing to
    forgo the benefits of object-oriented
    abstraction.</p>
  </blockquote>
  
  <p>That's a quote from "Effective Java" by Joshua Bloch and there's more on that subject in a great Artima article here:</p>
  
  <p><a href="http://www.artima.com/lejava/articles/equality.html" rel="noreferrer">http://www.artima.com/lejava/articles/equality.html</a></p>
  
  <p>And we're perfectly fine with that, this is not what this question is about.</p>
  
  <p>The question is: seen that it is a fact that in some case you cannot satisfy the <code>equals()</code> contract, what would be a clean way to automatically make <code>hashcode()</code> and <code>equals()</code> throw an UnsupportedOperationException?</p>
  
  <p>Would an annotation work?  I'm thinking about something like <code>@NotNull</code>: every <code>@NotNull</code> contract violation does throw an exception automatically and you have nothing else to do besides annotating your parameters/return value with <code>@NotNull</code>.</p>
  
  <p>It's convenient, because it's 8 characters ("@NotNull") instead of constantly repeating the same verification/throw exception code.</p>
  
  <p>In the case that I'm concerned about, in every implementation where <code>hashCode()/equals()</code> makes no sense, we're always repeating the same thing:</p>
  
  <pre><code>@Override
  public int hashCode() {
      throw new UnsupportedOperationException( "contract violation: calling hashCode() on such an object makes no sense" );
  }
  
  @Override
  public boolean equals( Object o ) {
      throw new UnsupportedOperationException( "contract violation: calling equals() on such an object makes no sense" );
  }
  </code></pre>
  
  <p>However this is error prone: we may by mistake forget to cut/paste this and it may results in users misusing such objects (say by trying to put them in the default Java collections).</p>
  
  <p>Or if annotation can't be made to create this behavior, would AOP work?</p>
  
  <p>Interestingly the real issue it the very presence of <code>hashCode()</code> and <code>equals()</code> at the top of the Java hierarchy which simply makes no sense in quite some cases.  But then how do we deal with this problem cleanly?</p>