class Base{} class Derived extends Base{} class HiDerived extends Derived{} /** * 2018/09/11 <<thinking in java>> RTTI * instanceof Class isInstance 等价性 * @author zz2108828 */ public class Test{ static void test (Object x) { System.out.println("-----------Current type: " + x.getClass()); System.out.println("x instance of Base " + (x instanceof Base)); System.out.println("x instance of Derived " + (x instanceof Derived)); System.out.println("x instance of HiDerived " + (x instanceof HiDerived)); System.out.println("Base.isInstance(x) " + Base.class.isInstance(x)); System.out.println("Derived.isInstance(x) " + Derived.class.isInstance(x)); System.out.println("HiDerived.isInstance(x) " + HiDerived.class.isInstance(x)); System.out.println("x.getClass() == Base.class "+ (x.getClass() == Base.class)); System.out.println("x.getClass() == Derived.class " + (x.getClass() == Derived.class)); System.out.println("x.getClass().equals(Base.class) " + x.getClass().equals(Base.class)); System.out.println("x.getClass().equals(Derived.class) "+x.getClass().equals(Derived.class)); System.out.println("x.getClass().isAssignableFrom(Base.class) " +(x.getClass().isAssignableFrom(Base.class))); System.out.println("x.getClass().isAssignableFrom(Derived.class) " +(x.getClass().isAssignableFrom(Derived.class))); System.out.println("x.getClass().isAssignableFrom(HiDerived.class) " +(x.getClass().isAssignableFrom(HiDerived.class))); } public static void main(String[] args) { test(new Base()); test(new Derived()); } }
-----------Current type: class Base
x instance of Base true
x instance of Derived false
x instance of HiDerived false
Base.isInstance(x) true
Derived.isInstance(x) false
HiDerived.isInstance(x) false
x.getClass() == Base.class true
x.getClass() == Derived.class false
x.getClass().equals(Base.class) true
x.getClass().equals(Derived.class) false
x.getClass().isAssignableFrom(Base.class) true
x.getClass().isAssignableFrom(Derived.class) true
x.getClass().isAssignableFrom(HiDerived.class) true
-----------Current type: class Derived
x instance of Base true
x instance of Derived true
x instance of HiDerived false
Base.isInstance(x) true
Derived.isInstance(x) true
HiDerived.isInstance(x) false
x.getClass() == Base.class false
x.getClass() == Derived.class true
x.getClass().equals(Base.class) false
x.getClass().equals(Derived.class) true
x.getClass().isAssignableFrom(Base.class) false
x.getClass().isAssignableFrom(Derived.class) true
x.getClass().isAssignableFrom(HiDerived.class) true