Java instanceof getClass() Java instanceof和getClass()区别实例解析
htj10 人气:0想了解Java instanceof和getClass()区别实例解析的相关内容吗,htj10在本文为您仔细讲解Java instanceof getClass()的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,instanceof,getClass(),下面大家一起来学习吧。
对象 instanceof 类名,表示 对象是类名的实例,或者是其子类的实例,返回 true,否则返回 false。
对象.getClass() == 类名.class ,表示 只有对象是该类的实例,才返回 true
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 Base{ } class Derived extends Base{ } public class Hello { public static void main(String[] args) throws ParseException { Derived d = new Derived(); boolean bRet; bRet = d instanceof Derived;//true bRet = d instanceof Base;//true bRet = d.getClass() == Derived.class;//true // bRet = d.getClass() == Base.class;// 出错 bRet = d.getClass().equals(Base.class);//false } }
使用,重写equals
class Person{ private String id; private String name; //重写equals()方法,提供自定义的相等标准 public boolean equals(Object obj){ if(this == obj)//若为同一个对象 return true; //只有当obj是Person对象 if(null != obj && obj.getClass() == Person.class){ Person p = (Person)obj; if(id.equals(obj).getId() && ...){ return true; } } return false; } }
加载全部内容