title: safe cast by a subclass type id in java
body: <p>I have a base <code>Entity</code> class:</p>
  
  <pre><code>public class Entity
  {
      abstract int getTypeID();
  }
  </code></pre>
  
  <p>The method <code>int getTypeID()</code> returns a number that is unique to that class:</p>
  
  <pre><code>public class OneEntity extends Entity
  {
      int getTypeID()
      {
          return 1; // Actually defined in a constants class
      }
  }
  </code></pre>
  
  <p>Now I want to be able to safely cast it and assign it. </p>
  
  <p>I can do it this way:</p>
  
  <pre><code>public void castTheEntityAndDoSomething(Entity ent)
  {
      if (isType(ent, 1)) // this is the 1 from the OneEntity class
      {
          OneEntity oneEnt = (OneEntity)ent;
  
          // ... and then do something
      }
  }
  
  public bool isType(Entity ent, int type)
  {
      return ent.getTypeID() == type;
  }
  </code></pre>
  
  <p>But what I'd like to do is combine the cast and the type check in one line. </p>
  
  <p>Something like:</p>
  
  <pre><code>if (OneEntity oneEnt = entityCast(ent, 1))
  {
      // use a method specific to the OneEntity class
  }
  </code></pre>
  
  <p>Is this possible? What does the method look like? 
  It would be even better if I could use the subclass name as an argument of the safe casting method. </p>
  
  <p>EDIT:</p>
  
  <p>So I've written this method to avoid the type id etc. etc. </p>
  
  <pre><code>@SuppressWarnings("unchecked")
  public static &lt;T extends Entity&gt; T castEntity(Entity ent)
  {
      if (ent instanceof T)
      {
          return (T)ent;
      }
  
      return null;
  }
  </code></pre>
  
  <p>But it has this error:</p>
  
  <p>Cannot perform instanceof check against type parameter T. Use instead its erasure Entity since generic type information will be erased at runtime</p>
  
  <p>What do I need to do to fix this compile error? Is this even going in the right direction?</p>