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 => trueo1 instanceof B => falseo2 instanceof A => true // <================ HEREo2 instanceof B => trueo1.getClass().equals(A.class) => trueo1.getClass().equals(B.class) => falseo2.getClass().equals(A.class) => false // <===============HEREo2.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; }}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
