Is instanceof illegal in this case?

My textbook says that one of the restrictions on generic types is that instanceof tests and typecasts will not work, and will only work with the raw type. I know that instanceof tests to see if an object is of a specified type, but why doesn't that an typecasting work with generic types?
Who is Participating?
for_yanConnect With a Mentor Commented:

read this from
really clears many questions similar to yours above:

The compiler translates generic and parameterized types by a technique called type erasure .  Basically, it elides all information related to type parameters and type arguments. For instance, the parameterized type List<String> is translated to type List , which is the so-called raw type .  The same happens for the parameterized type List<Long> ; it also appears as List in the bytecode.

After translation by type erasure, all information regarding type parameters and type arguments has disappeared. As a result, all instantiations of the same generic type share the same runtime type, namely the raw type.

Example (printing the runtime type of two parameterized types):

    System.out.println("runtime type of ArrayList<String>: "+ne w ArrayList<String>().getClass());
    System.out.println("runtime type of ArrayList<Long>  : "+new ArrayList<Long>().g etClass());

    prints:   runtime type of ArrayList<String> : class java.util. ArrayList
          runtime type of ArrayList<Long>   : class java.util. ArrayList

The example illustrates that ArrayList<String> and ArrayList<Long> share the runtime type ArrayList .

check here:

Generics are a compile time feature. Generics add checks at compile time which may not have any meaning at runtime. This is one example. You can only check the type of the object referenced which could be a super type in code. If you want to pass the type T you have do this explicitly.

void someMethod(Class<T> tClass) {


void someMethod(Class<T> tClass, T tArg) {

Note: the type might not be the same,

someMethod(Number.class, 1);

Never miss a deadline with

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.


With unboundedd wildcard "?" you can use generics in instanceof, but
these generics with unbounded wildcard are very close to non-gereic (raw) tyoes
reda here:

The raw type and the unbounded wildcard parameterized type have a lot in common.  Both act as kind of a supertype of all instantiations of the corresponding generic type.  Both are so-called reifiable types. Reifiable types can be used in instanceof expressions and as the component type of arrays, where non-reifiable types (such as concrete and bounded wildcard parameterized type) are not permitted.
shampouyaAuthor Commented:
All Courses

From novice to tech pro — start learning today.