在查询类信息时,instanceof、isInstance()产生的结果相同,==、equals产生的结果相同。示例:
class Parent {
}
class Son extends Parent {
}
public class Test {
public static void main(String[] args) {
test(new Parent());print("\n");test(new Son());}private static void test(Object o) {
print("Testing o of type:"+o.getClass());//instanceofprint("o instanceof Parent:"+(o instanceof Parent));print("o instanceof Son:"+(o instanceof Son));//isInstanceprint("Parent.isInstance(o):"+ Parent.class.isInstance(o));print("Son.isInstance(o):"+ Son.class.isInstance(o));//==print("o.getClass == Parent.class :"+(o.getClass()==Parent.class));print("o.getClass == Son.class :"+(o.getClass()==Son.class));//equalsprint("o.getClass.equals(Parent.class) :"+(o.getClass().equals(Parent.class)));print("o.getClass.equals(Son.class) :"+(o.getClass().equals(Son.class)));}private static void print(String s){
System.out.println(s);}
}
结果:
Testing o of type:class com.freesky.basic.classt.Parent
o instanceof Parent:true
o instanceof Son:false
Parent.isInstance(o):true
Son.isInstance(o):false
o.getClass == Parent.class :true
o.getClass == Son.class :false
o.getClass.equals(Parent.class) :true
o.getClass.equals(Son.class) :falseTesting o of type:class com.freesky.basic.classt.Son
o instanceof Parent:true
o instanceof Son:true
Parent.isInstance(o):true
Son.isInstance(o):true
o.getClass == Parent.class :false
o.getClass == Son.class :true
o.getClass.equals(Parent.class) :false
o.getClass.equals(Son.class) :true
instanceof、isInstance()保持了类型的概念,指的是“你是这个类,或者是这个累的派生类吗?”;==、equals比较的是实际的、确切的Class对象,没有考虑继承