1

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?

2
  • 1
    instanceof is a runtime comparison. Generics are a compile-time constraint that do not exist at runtime. You can only do other instanceof Peach. Commented Nov 15, 2018 at 17:44
  • FWIW, I can't ever remember a situation where what you're proposing was necessary. I very rarely need instanceof at all, let alone with reified generics. If you need to rely on this, your design is almost certainly wrong. Commented Nov 15, 2018 at 17:49

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.