• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
萝莉神控
博客园    首页    新随笔    联系   管理    订阅  订阅

instanceof关键字

instanceof关键字是一个双目运算符,用来判断一个对象是否是该类的实例

boolean result = obj instanceof Class

 

1、obj必须为引用类型,不能为基本类型

int i = 0;

System.out.println(i.instanceof(Integer));//return false

System.out.println(i.instanceof(Object));//return false

2、obj为null则返回false

System.out.println(null.instanceof(Object));//return false

3、obj为class类的实例对象

Integer i = new Integer();

System.out.println(i.instanceof(Integer));//return true

4、obj为接口的实现类

ArrayList arrayList = new ArrayList();

System.out.println(arrayList.instanceof(List));//return true

List list = new ArrayList();

System.out.println(list.instanceof(ArrayList));//return true

5、obj为类的直接或间接子类

class Person{

}

class Man extends Person{

}

Person person1  = new Person();

Person person2 = new Man();

Man man = new Man();

System.out.println(person1.instanceof(Man));//return false

System.out.println(person2.instanceof(Man));//return true

System.out.println(man.instanceof(Man));//return true

posted @ 2019-10-15 17:44  萝莉神控  阅读(431)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3