java中instanceof和getClass()的区别分析
2016-03-15 09:49
555 查看
class A { }
class B extends A { }
Object o1 = new A();
Object o2 = new B();
o1 instanceof A => true
o1 instanceof B => false
o2 instanceof A => true // <================ HERE
o2 instanceof B => true
o1.getClass().equals(A.class) => true
o1.getClass().equals(B.class) => false
o2.getClass().equals(A.class) => false // <===============HERE
o2.getClass().equals(B.class) => true
getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with.
class B extends A { }
Object o1 = new A();
Object o2 = new B();
o1 instanceof A => true
o1 instanceof B => false
o2 instanceof A => true // <================ HERE
o2 instanceof B => true
o1.getClass().equals(A.class) => true
o1.getClass().equals(B.class) => false
o2.getClass().equals(A.class) => false // <===============HERE
o2.getClass().equals(B.class) => true
getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with.
相关文章推荐
- 快速了解Log4J
- JAVA反射机制
- Java构造器
- springMVC基础
- QML中的SpringAnimation弹簧震荡动画
- springMVC3学习(四)--訪问静态文件如js,jpg,css
- SpringAOP注解方式监控方法执行情况
- Java序列化与反序列化
- Spring配合Junit进行单元测试
- 同一个WildFly服务器中的war应用调用本地ear服务
- 学习scala的点点滴滴(2)-与java交互
- Eclipse问题 A cycle was detected in the build path of project: XXX
- Java Collection List Set Map 的区别
- Struts2、Spring3.2.4、Mybatis和Mysql数据库整合开发
- eclipse 编码设置
- 原 Eclipse Luna安装Weblogic Server Tools插件及配置Weblogic
- javax.el.PropertyNotFoundException: Property 'Name' not found on type com.min.test.User
- maven web 项目中启动报错java.lang.ClassNotFoundException
- java JVM 垃圾回收算法不完全总结
- JavaBean规范