Java: Instanceof and Generics

Viewed 210508

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?

9 Answers

Let Java determine it and catch the exception bottom line.

public class Behaviour<T> {
    public void behave(Object object) {
        T typedObject = null;
        
        try { typedObject = (T) object; }
        catch (ClassCastException ignored) {}
        
        if (null != typedObject) {
            // Do something type-safe with typedObject
        }
    }
}
Related