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.
instanceofis a runtime comparison. Generics are a compile-time constraint that do not exist at runtime. You can only doother instanceof Peach.instanceofat all, let alone with reified generics. If you need to rely on this, your design is almost certainly wrong.