标签:except str title color void 使用 subclass tps ==
对象 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; } }
另外:[Java] Java instanceof 和 Class.isInstance()区别与应用
标签:except str title color void 使用 subclass tps ==
原文地址:https://www.cnblogs.com/htj10/p/13377765.html