gpt4 book ai didi

java - 为什么在 T 是类型参数而 t 是变量的情况下不允许使用 "t instanceof T"?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:46:08 28 4
gpt4 key购买 nike

Eclipse 表示由于泛型类型橡皮擦,类型参数不允许使用 instanceof 操作。

我同意在运行时不会保留任何类型信息。但是请考虑以下类的通用声明:

class SomeClass<T>{
T t;
SomeClass(Object o){
System.out.println(o instanceof T); // Illegal
}
}

在运行时,不会出现 T!但是如果我实例化这个Integer类型的类,那么对应的对象就会有一个Integer类型的字段t。

那么,为什么我不能用 T 检查一个变量的类型,它可以在运行时被 Integer 替换。我实际上会做类似“o instanceof Integer”的事情。

在哪些情况下,允许带有类型参数的 instanceof 会导致麻烦,以至于被禁止?

最佳答案

But if I instantiate this class of type Integer, then the corresponding object will have a field t of type Integer

不,不会。它将有一个对象类型的字段。只是每次您访问它时,它都会被转换为一个整数。

考虑以下代码:

SomeClass<Integer> c = new SomeClass<Integer>();
SomeClass untyped = (SomeClass)c; // Which type was it?
SomeClass<String> stringTyped = (SomeClass<String>)untyped; // Now it's STRING??

有效。给你一堆编译器警告,但有效。因为字段 T 实际上是 Object 类型,可以转换为任何类型。

关于java - 为什么在 T 是类型参数而 t 是变量的情况下不允许使用 "t instanceof T"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8741984/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com