Reputation: 799
My interface has a generic type argument. Any class which would implement the interface has to declare this type, so later users of it will know what they get back. Now, I need to do checks with instanceof on these classes to see if they are an instance of Action.
My question is: what will instanceof return if i did:
if (SomeAction instanceof Action<?>) {
. . .
}
with this SomeAction
class:
public class SomeAction implements Action<String> {
. . .
}
Will it return true, or false? And what if I did SomeAction instanceof Action<Integer>
Upvotes: 1
Views: 1678
Reputation: 3337
I implemented it and it returns true.
Also if you leave out generics all together, like this:
if (SomeAction instanceof Action) {
. . .
}
If you try to actually include a generic type for Action in that if operation the code doesn't compile, with the message:
illegal generic type for instance of
for instance:
if (action instanceof Action<String>) {
System.out.println("is Action");
} else {
System.out.println("is not Action");
}
Upvotes: 0
Reputation: 46219
Java doesn't care about the generic type when you use instanceof
. To quote the Javadocs:
Because the Java compiler erases all type parameters in generic code, you cannot verify which parameterized type for a generic type is being used at runtime
So, you can test against Action<?>
or Action
, but you will get a compiler error if you try to test against Action<Integer>
. The error message is very informative:
Cannot perform instanceof check against parameterized type Action<Integer>. Use the form Action<?> instead since further generic type information will be erased at runtime
Upvotes: 4