java - 接口(interface)泛型和 instanceof

标签 java generics interface instanceof

我的接口(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/

相关文章:

c# - 通用函数和新约束

java - 如何在启动画面上加载主屏幕?

generics - 使用接受闭包的方法在 Rust 中创建对象安全特征

typescript - 如何在 TypeScript 中定义通用对象数组,每个项目都有不同的模板参数

java - 如何避免从父类(super class)进行转换?

c# - 从 GeckoFx C# 中删除 cookie

c# - 接口(interface)应该尽可能通用吗?

java - Java 中 MS Excel 的 Linest 函数

java - 在每个 '<br>' -Tag 处将字符串拆解为数组

java - JXTreeTable 上的固定列