我的接口(interface)有一个通用类型参数。任何实现该接口(interface)的类都必须声明此类型,以便以后的用户知道他们得到了什么。现在,我需要用 instanceof 对这些类进行检查,看看它们是否是 Action 的实例。
我的问题是:如果我这样做了,instanceof 会返回什么:
if (SomeAction instanceof Action<?>) {
. . .
}
有了这个SomeAction
类:
public class SomeAction implements Action<String> {
. . .
}
它会返回 true 还是 false?如果我这样做了怎么办 SomeAction instanceof Action<Integer>
最佳答案
当您使用 instanceof
时,Java 不关心泛型类型.引用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
因此,您可以针对 Action<?>
进行测试或 Action
, 但如果您尝试针对 Action<Integer>
进行测试,则会出现编译器错误.错误消息非常有用:
Cannot perform instanceof check against parameterized type Action<Integer>. Use the form Action<?> instead since further generic type information will be erased at runtime
关于java - 接口(interface)泛型和 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16751858/