1.instanceof isInstanceof考虑的继承关系。指你是这个类吗?你是这个类的派生类吗?(后者需要通过class对象 去比较)
public class FamilyVsExacType {
static void test(Object o){
//instanceof 和isInstanceof考虑的继承关系。
System.out.println("o.getClass"+o.getClass());
System.out.println("o instanceof Base "+(o instanceof Base));
System.out.println("o instanceof Dirved "+(o instanceof Drived));
System.out.println("Base.isInstanceof(o) "+(Base.class.isInstance(o)));
System.out.println("Drived.isInstanceof(o) "+(Drived.class.isInstance(o)));
System.out.println("================================");
}
public static void main(String[] args) {
test(new Drived());
System.out.println();
test(new Base());
}
Output:
o.getClassclass com.package14.Two.Drived
o instanceof Base true
o instanceof Dirved true
Base.isInstanceof(o) true
Drived.isInstanceof(o) true
o.getClassclass com.package14.Two.Base
o instanceof Base true
o instanceof Dirved false
Base.isInstanceof(o) true
Drived.isInstanceof(o) false
** 2.==和equals在比较Class对象时只比较具体的值不考虑继承关系,_**
ublic class FamilyVsExacType {
static void test(Object o){
//==和equals只比较具体的值不考虑继承关系
System.out.println("o.class==Base.class "+(o.getClass()==Base.class));
System.out.println("o.class==Drived.class "+(o.getClass()==Drived.class));
System.out.println("o.getClass.equals(Base.class) "+(o.getClass().equals(Base.class)));
System.out.println("o.getClass.equals(Dirved.class) "+(o.getClass().equals(Drived.class)));
}
public static void main(String[] args) {
test(new Drived());
System.out.println();
test(new Base());
}
OutPut:
o.class==Base.class false
o.class==Drived.class true
o.getClass.equals(Base.class) false
o.getClass.equals(Dirved.class) true
================================
o.class==Base.class true
o.class==Drived.class false
o.getClass.equals(Base.class) true
o.getClass.equals(Dirved.class) false
注意:同一类的不同实列的Class对象相同(每一个类有一个Class对象)
Base base = new Base();
Base base2 = new Base();
//同一个类的实例的Class对象指向同一个Class对象
Class<? extends Base> aClass = base.getClass();
Class<? extends Base> aClass1 = base2.getClass();
System.out.println(aClass1==aClass1);
output:
true