title: Check if object is cast to its dynamic type in Java
body: <p>I would like to know if there is a way to check if an reference has been cast to the exact Type of its object. For example...</p>
  
  <pre><code>String s = new String("test");
  checkCast(s); //Returns true, since s has a dynamic and static type of String.
  Object o = (Object) s;
  checkCast(o); //Returns false, since the dynamic and static type of o are not equal.
  </code></pre>
  
  <p>Some background about the actual problem...</p>
  
  <p>I have a hierarchy of classes A, B, and C like below:</p>
  
  <pre><code>class A {}
  class B extends A {}
  class C extends B {}
  </code></pre>
  
  <p>And then I have a <code>LinkedList&lt;A&gt;</code> of A objects. This list may contain any of the above classes. I then have a method like so...</p>
  
  <pre><code>&lt;T extends A&gt; T getFirstObjInList(){
     //Iterate over the list and return the first object that is of type T...
  }
  </code></pre>
  
  <p><strong>I need to know how to check if an object from my list is of the Generic Type passed into the method.</strong> I can't use instanceof because erasure etc. and I'd really prefer to not change the method's heading, i.e., adding any parameters or anything like that.</p>
  
  <p>What I first tried doing is casting each object in the list to T in a for loop, and if a ClassCastException is thrown, continue iterating, but that obviously didn't work with the hierarchy I have, so now I'm looking for a way to check if an object has been casted to its dynamic type. <strong>If the object in the list is of the type specified, then when casted, its static type won't change,</strong> so if i can compare the two types, I can figure out if the object is an instance of the generic type given.</p>
  
  <p>Note: <code>list.getFirst() instanceof T</code> doesn't compile due to type erasure.</p>