Adrian Markoe
Adrian Markoe

Reputation: 53

How to test instanceof on a generic class?

I have an equals() method that contains this code:

if (other instanceof Peach<K, V>) {
    ...
}

However, this does not compile. How to fix this line of code?

Upvotes: 1

Views: 96

Answers (2)

Magnilex
Magnilex

Reputation: 11958

As already pointed out, this is not possible. I would like to add that this is because of what is known as Type Erasure. The official Java tutorial has the following short summary:

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:

  • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
  • Insert type casts if necessary to preserve type safety.
  • Generate bridge methods to preserve polymorphism in extended generic types.

Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

The key here is "The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.". Because of this, it is not possible, to do the instanceof check you seek to do.

Upvotes: 2

minus
minus

Reputation: 2786

In short, you can't. Java erases generics types, so, at runtime, you don't have this information anymore.

You can use

if (other instanceof Peach) {
    ...
}

Upvotes: 1

Related Questions