title: Check instance with java.lang.reflect.Type
body: <p>I'm looking for a way to find out if an object <code>x</code> is an instance
  of a generic type. For example <code>List&lt;String&gt;</code>.</p>
  
  <p>Inspired by the Super-Type-Token idiom I can retrieve the <code>java.lang.reflect.Type</code> at runtime with follwing code</p>
  
  <pre><code>import java.lang.reflect.ParameterizedType;
  import java.lang.reflect.Type;
  import java.util.List;
  
  public class Test {
  
      public static void main(String[] args) {
          TypeReference&lt;List&lt;String&gt;&gt; ref = new TypeReference&lt;List&lt;String&gt;&gt;() {};
          System.out.println(ref.getType());
          System.out.println(ref.getType().getClass());
      }
  
      abstract static class TypeReference&lt;T&gt; {
          private final Type type;
  
          protected TypeReference() {
              ParameterizedType superclass = (ParameterizedType) getClass().getGenericSuperclass();
              type = superclass.getActualTypeArguments()[0];
          }
  
          public Type getType() {
              return type;
          }
      }
  }
  </code></pre>
  
  <p>The output is</p>
  
  <pre><code>java.util.List&lt;java.lang.String&gt;
  class sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
  </code></pre>
  
  <p>How can I use this information for dynamic casting or type checking?</p>
  
  <p><sup>Background is I'm currently writing a heterogeneous type-safe container lib and want to add support for generic types <a href="https://bitbucket.org/mbeyene/jam" rel="nofollow">https://bitbucket.org/mbeyene/jam</a></sup></p>