小知了
一个不神奇的博客
instanceOf,isInstance,Class,isAssignableFrom区别比较
2017-01-25 21:40:33   阅读373次

instanceOf和isInstance()执行类型检查的时候考虑到了继承结构,并且比较的是实例化后的对象。==和equals比较的是实际对象对应的Class对象,没有考虑继承结构。

A instanceOf B                      A是否是B的子类或B类型的

A.class.isInstance(B.class)              A的子类有没有B

A.class == B.class  or  A.class.equals(B.class)   A.B的两类是否相同

A.class.isAssignableFrom(B.class);             A的子类有没有B    

以上 类.class均可以写成类.getClass()

看一个例子:

class Base {}

class Derived extends Base {}

public class FamilyVsExactType {
  public static void test(Object x) {
      String name = x.getClass().getSimpleName();
    print(""+name+" instanceof Base " + (x instanceof Base));
    print(""+name+" instanceof Derived "+ (x instanceof Derived));
    print("Base.isInstance("+name+") "+ Base.class.isInstance(x));
    print("Derived.isInstance("+name+") " +Derived.class.isInstance(x));
    print(""+name+".getClass() == Base.class " +(x.getClass() == Base.class));
    print(""+name+".getClass() == Derived.class " + (x.getClass() == Derived.class));
    print(""+name+".getClass().equals(Base.class)) "+(x.getClass().equals(Base.class)));
    print(""+name+".getClass().equals(Derived.class)) " + (x.getClass().equals(Derived.class)));
    print("-----------------------------------------------------------------");
  }
  public static void main(String[] args) {
    test(new Base());
    test(new Derived());
    print("Base.class.isAssignableFrom(Derived.class) "+Base.class.isAssignableFrom(Derived.class));
    print("Derived.class.isAssignableFrom(Base.class) "+Derived.class.isAssignableFrom(Base.class));
  }
}

输出:

Base instanceof Base true
Base instanceof Derived false
Base.isInstance(Base) true
Derived.isInstance(Base) false
Base.getClass() == Base.class true
Base.getClass() == Derived.class false
Base.getClass().equals(Base.class)) true
Base.getClass().equals(Derived.class)) false
-----------------------------------------------------------------
Derived instanceof Base true
Derived instanceof Derived true
Base.isInstance(Derived) true
Derived.isInstance(Derived) true
Derived.getClass() == Base.class false
Derived.getClass() == Derived.class true
Derived.getClass().equals(Base.class)) false
Derived.getClass().equals(Derived.class)) true
-----------------------------------------------------------------
Base.class.isAssignableFrom(Derived.class) true
Derived.class.isAssignableFrom(Base.class) false

直接看输出或许更加直观!

参考《Java编程思想》P334



-----------------------------------------------------
转载请注明来源此处
原地址:#

-----网友评论----
暂无评论
-----发表评论----
微网聚博客乐园 ©2014 blog.mn886.net 鲁ICP备14012923号   网站导航