title: Java generics parameter bounding to any of a range of types
body: <p>Is there a syntax or workaround to constrain a generic type parameter to <em>any</em> of a range of types?</p>
  
  <p>I am aware that you can constrain a type to be <em>all</em> of a range of types (ie <code>AND</code> logic):</p>
  
  <pre><code>public class MyClass&lt;T extends Comparable&lt;T&gt; &amp; Serializable&gt; { } // legal syntax
  </code></pre>
  
  <p>Is there an <code>OR</code> logic version, ie something like this:</p>
  
  <pre><code>public class MyClass&lt;T extends Comparable&lt;T&gt; | Serializable&gt; { } // illegal syntax
  </code></pre>
  
  <p>If there isn't a syntax that supports this (I don't think there is), is there a workaround or approach that is a good pattern?</p>
  
  <p>For some context, one example use case might be:</p>
  
  <pre><code>/** @return true if the obj is either has the same id, or if obj is the same as id */
  public &lt;T extends MyClass | String&gt; boolean sameAs(T obj) {
      if (obj instanceof String) return this.id.equals(obj);
      if (obj instanceof MyClass) return this.id.equals(((MyClass)obj).id);
      return false;
  }
  </code></pre>
  
  <p>People seem to be getting hung up on the exact semantic of my method example above. Let's try this instead:</p>
  
  <pre><code>public class MyWrapper&lt;T extends A | B&gt; {
      // my class can wrap A or B (unrelated classes). Yes I will probably use instanceof
  }
  </code></pre>
  
  <p><strong>EDITED:</strong><br>
  I won't know at compile time which I might get (coming from external code), so I want to avoid having concrete classes for each type. Also, I have to give my class to a foreign system who invokes my class.method, but the other system can give me instances of a variety of classes, but a <em>narrowly defined</em> and known variety.</p>
  
  <p>Some people have commented on <code>instanceof</code> being "impure". Well, one workaround is to use a factory method to pick my concrete class based on the class of the incoming object, but that factory method would have to use <code>instanceof</code>, so you're just moving the <code>instanceof</code> to another place - you still need the <code>instanceof</code>.</p>
  
  <p>Or is this idea just not ever a good one?</p>