class Base{}class Derived extends Base{}class HiDerived extends Derived{}/** * 2018/09/11 <> 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 truex instance of Derived falsex instance of HiDerived falseBase.isInstance(x) trueDerived.isInstance(x) falseHiDerived.isInstance(x) falsex.getClass() == Base.class truex.getClass() == Derived.class falsex.getClass().equals(Base.class) truex.getClass().equals(Derived.class) falsex.getClass().isAssignableFrom(Base.class) truex.getClass().isAssignableFrom(Derived.class) truex.getClass().isAssignableFrom(HiDerived.class) true-----------Current type: class Derivedx instance of Base truex instance of Derived truex instance of HiDerived falseBase.isInstance(x) trueDerived.isInstance(x) trueHiDerived.isInstance(x) falsex.getClass() == Base.class falsex.getClass() == Derived.class truex.getClass().equals(Base.class) falsex.getClass().equals(Derived.class) truex.getClass().isAssignableFrom(Base.class) falsex.getClass().isAssignableFrom(Derived.class) truex.getClass().isAssignableFrom(HiDerived.class) true