Discuss / Java / 局限三有问题。"hello" instanceof String.class 也没这种用法啊,应该是"hello" instanceof String

局限三有问题。"hello" instanceof String.class 也没这种用法啊,应该是"hello" instanceof String

Topic source

kylechli

#1 Created at ... [Delete] [Delete and Lock User]
p instanceof Pair<String>.class

p instanceof Pair<Integer> //可以的

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

p instanceof Pair<Integer>

无法编译

kylechli

#3 Created at ... [Delete] [Delete and Lock User]

我发现jdk14下面 可以写p instanceofPair<Integer>, 而jdk8只能写p instanceofPair

Pair<Integer> p = new Pair<>(123, 456);  

if (p instanceof Pair<Integer>) {  

            System.out.println(true);  

}

可以编译的p instanceof Pair<Integer>和p instanceof Pair 都可以

p instanceof Pair<String> 编译会出错

廖雪峰

#5 Created at ... [Delete] [Delete and Lock User]

你都知道了p是Pair<Integer>后面再判断有什么意义?

Pair<Integer> p = ...
if (p instanceof Pair<Integer>) {
   ...
}

如果你不知道p的类型又编译不过:

Object p = ...;
if (p instanceof Pair<String>) { // compile error
}

所以instanceof根本无法判断带泛型的类型


  • 1

Reply