简体   繁体   中英

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?

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.

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) {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM