Java: Instanceof and Generics

Nick Heiner picture Nick Heiner · Oct 15, 2009 · Viewed 176.7k times · Source

Before I look through my generic data structure for a value's index, I'd like to see if it is even an instance of the type this has been parametrized to.

But Eclipse complains when I do this:

@Override
public int indexOf(Object arg0) {
    if (!(arg0 instanceof E)) {
        return -1;
    }

This is the error message:

Cannot perform instanceof check against type parameter E. Use instead its erasure Object since generic type information will be erased at runtime

What is the better way to do it?

Answer

Yishai picture Yishai · Oct 15, 2009

The error message says it all. At runtime, the type is gone, there is no way to check for it.

You could catch it by making a factory for your object like this:

 public static <T> MyObject<T> createMyObject(Class<T> type) {
    return new MyObject<T>(type);
 }

And then in the object's constructor store that type, so variable so that your method could look like this:

        if (arg0 != null && !(this.type.isAssignableFrom(arg0.getClass()))
        {
            return -1;
        }