instanceof 与 getClass()的区别
来源:互联网 发布:易语言软件破解 编辑:程序博客网 时间:2024/06/01 12:43
1、使用
判断两个对象是否相等的时候,在equals()方法中通常使用instanceof运算符或者getClass()方法来判断equals()参数的类型。如下所示:
public class Account { private String accountNo; public Account() { } public Account(String accountNo) { this.accountNo = accountNo; } public getAccountNo() { return accountNo; } public int hashCode() { return accountNo.hashCode(); } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj != null && obj.getClass() == Account.class) { Account target = (Account) obj; return target.getAccountNo().equals(accountNo); } return false; }}
或者
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj != null && obj instanceof Account) { Account target = (Account) obj; return target.getAccountNo().equals(accountNo); } return false; }
2、区别
1、示例代码:
class Parent{ }class Child extends Parent{ }public class Test { public static void main(String[] args){ Parent parent = new Parent(); Child child = new Child (); System.out.println(child.getClass() == Parent.class); System.out.println(child.getClass() == Child.class); System.out.println(child instanceof Parent); System.out.println(child instanceof Child); }}// 输出false, true, true, true
2、原因:
(1)instanceof用来判断一个对象是否是某一类型的实例时,该类型可以是父类或者接口。而getClass()用于判断准确的类型。
(2)同时,在这里必须说明的是,getClass()判断的是该变量实际指向的对象的类型(即运行时类型),跟声明该变量的类型无关。即,上面代码中:
Child child = new Child();// 改为Parent child = new Child();
结果不变。
3、总结
(1) instanceof:
java 中的instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例。
instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。
S(Object) instanceof T(Class)
简单来说,instanceof就是判断对象S是否是T类的实例,或者是T类的子类实例。
(2)getClass()方法在JDK1.8中定义如下:
/*** Returns the runtime class of this Object*/public final native Class<?> getClass();
功能:返回在运行时期对象的类。
使用场景:getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with.
参考文献:
java中instanceof和getClass()的作用
阅读全文
0 0
- instanceof 与 getClass()的区别
- java-----instanceof与getClass的区别
- instanceof和getClass()的区别
- instanceof 和 getclass 的区别
- java instanceof和getClass()的区别
- (十一)instanceof 和 getclass 的区别
- java instanceof和getClass()的区别以及继承与组合的区别
- Rhyme/Java getClass()与instanceof的区别以及如何编写一个完美的equals()
- super.getClass()与this.getClass() 的区别
- 一个对象使用instanceof 和getClass的区别
- 从一个例子学习 instanceof 和 getclass 的区别
- getClass()与getSimpleName()的区别
- 8.21 实习总结 instanceof 与 .getclass()
- isAssignableFrom 与 instanceof 的区别
- isAssignableFrom 与 instanceof 的区别
- isAssignableFrom与instanceof的区别
- typeof 与instanceof 的区别
- typeof与instanceof的区别
- 第四周项目一 建立单链表
- Cache写机制:Write-through与Write-back
- 对监督学习和无监督学习很好的解释,通俗易懂
- 回归任务偏差与方差
- 高二&高一&初三模拟赛18 总结
- instanceof 与 getClass()的区别
- 求任意整数n的阶乘
- 简单描述为什么编译Android C程序所用的交叉编译工具链是arm-linux-androideabi-xx不是GNU开发的工具链arm-linux-gnueabi-xx?
- ORACLE PACKAGE 包详解
- 网络通信socket连接数上限
- 中国物联网产业应用联盟——物联网产业知识培训一期
- iOS 应用架构
- Caused by: java.sql.BatchUpdateException: Data truncation: Data too long for column 'JLFSM' at row 1
- Android DragGridView的简单介绍