title: Checking generic type
body: <p>The Java Collections interfaces (for example, <code>List</code> or <code>Set</code>) define the <code>contains</code> method to accept any Object.</p>
  
  <pre><code> public boolean contains(Object o)
  </code></pre>
  
  <p>However, when it comes to implementing this method, the particular collection I'm working on requires that I have a type which is compatible with the generic type <code>E</code> of the class (i.e. either be class E, or a subclass of E, or a class which implements E if E is an interface). In other words, if o is castable to type E, then it is compatible. This presents an issue because Java erases the Generic type information, so something like this isn't possible:</p>
  
  <pre><code>public boolean contains(Object o)
  {
      if(o instanceof E) // compile error due to type erasures
      {
          // ... check if this collection contains o
      }
      return false;
  }
  </code></pre>
  
  <p>My question is what would be the best way to accomplish something like this? The <a href="http://download.oracle.com/javase/tutorial/java/generics/erasure.html" rel="nofollow">Oracle Article on Type Erasures</a> mentions that this forbidden, but does not offer any solutions to this problem.</p>
  
  <p>I can only think of one semi-elegant way to get around this:</p>
  
  <p>Make a cast to type E. If the cast fails, o cannot be type E or a subclass of type E.</p>
  
  <pre><code>public boolean contains(Object o)
  {
      try
      {
          E key = (E) o; // I know it's unsafe, but if o is castable to E then the method should work
          // check if this collection contains key
      }
      catch(ClassCastException e)
      {
          // invalid type, cannot contain o
      }
      return false;
  }
  </code></pre>
  
  <p>While this would work, it looks messy (I'm not a big fan of using Exceptions in this manner).</p>
  
  <p>Is there a better way to accomplish this same goal (changing the method signature is not allowed)?</p>
  
  <p>edit: yeah, this doesn't work because E gets erased to Object :(</p>