java instanceof 有泛型参与时 没有继承关系编译不报错?

我还会大跳 2020-08-10 05:44:34


public class Test {
public static void main(String[] args) {
List<A> aList = new ArrayList<>();
A a = new A();
System.out.println(aList instanceof A); // 编译能通过?
System.out.println(aList instanceof List<B>); // 编译不能通过?
System.out.println(aList instanceof List<A>); // 编译不能通过?
System.out.println(a instanceof List<?>); // 编译能通过?
System.out.println(a instanceof List); // 编译能通过?
// A 和 List 不在同一个继承树,为什么能够通过编译?
}
}

class A {
}

class B {
}

1.A 与List没有继承关系,为什么编译能通过?
2.aList instanceof List<A> 为什么编译不通过?
...全文
3060 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
timi先生 2020-08-11
  • 打赏
  • 举报
回复
instanceof 不是用来检测实例是不是属于类的吗,和是不是继承貌似没关系吧
weixin_45684903 2022-02-16
  • 举报
回复
@timi先生 当然有关系 没有继承关系也就没必要检查是不是实例了直接就会报错
qq_39936465 2020-08-11
  • 打赏
  • 举报
回复
引用 3 楼 DSQ2544404641 的回复:
能再解释一下吗 List<A> aList = new ArrayList<>(); A a = new A(); B b = new B(); System.out.println(b instanceof A); // A和B没有继承关系,所以编译不通过 System.out.println(aList instanceof A); // List 和 A也没有继承关系, 为什么能通过?
boolean result = obj instanceof Class 注意:编译器会检查 obj 是否能转换成右边的class类型,如果不能转换则直接报错,如果不能确定类型,则通过编译,具体看运行时定。 List是泛用型无法判断类型所以通过编译。
我还会大跳 2020-08-11
  • 打赏
  • 举报
回复
引用 4 楼 lkj2016 的回复:
看看instanceof 自己百度,和别的弄混了吧,不会编译不通过的,最多报false,没有继承关系就运行阶段输出false,怎么可能编译阶段出错。
你可以复制代码自己看看,instanceof 的内容我百度过,找了很多没有找到我说的这个问题
qq_39936465 2020-08-11
  • 打赏
  • 举报
回复
引用 楼主 DSQ2544404641 的回复:
1.A 与List没有继承关系,为什么编译能通过? 2.aList instanceof List<A> 为什么编译不通过?
楼上说的正确 举个例子来说 List<A> aList = new ArrayList<>(); List<B> bList = new ArrayList<>(); System.out.println(aList.getClass());//输出 class java.util.ArrayList System.out.println(aList.getClass() == bList.getClass());//输出:true 所以aList instanceof List<A>这里List<A>没有意义,被认为是语法错误。
丿Mars丨巛恋 2020-08-11
  • 打赏
  • 举报
回复
首先建议你先去看看instanceof的用法,A instanceof B,A是不是B类型,注意是类型,不是实例
lkj2016 2020-08-11
  • 打赏
  • 举报
回复
看看instanceof 自己百度,和别的弄混了吧,不会编译不通过的,最多报false,没有继承关系就运行阶段输出false,怎么可能编译阶段出错。
我还会大跳 2020-08-10
  • 打赏
  • 举报
回复
引用 1 楼 lkj2016 的回复:
https://www.cnblogs.com/lzq198754/p/5780426.html 编译不通过原因,泛型擦除机制,所以报错 编译通过原因,为什么不通过呢,这又不是assert, 不会产生报错,只产生结果true or false。instanceof只进行判断相当于.equals在最低端实现了
能再解释一下吗 List<A> aList = new ArrayList<>(); A a = new A(); B b = new B(); System.out.println(b instanceof A); // A和B没有继承关系,所以编译不通过 System.out.println(aList instanceof A); // List 和 A也没有继承关系, 为什么能通过?
我还会大跳 2020-08-10
  • 打赏
  • 举报
回复
List<A> aList = new ArrayList<>(); A a = new A(); B b = new B(); System.out.println(b instanceof A); // A和B没有继承关系,所以编译不通过 System.out.println(aList instanceof A); // List 和 A也没有继承关系, 为什么能通过?
lkj2016 2020-08-10
  • 打赏
  • 举报
回复
https://www.cnblogs.com/lzq198754/p/5780426.html 编译不通过原因,泛型擦除机制,所以报错 编译通过原因,为什么不通过呢,这又不是assert, 不会产生报错,只产生结果true or false。instanceof只进行判断相当于.equals在最低端实现了

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧