企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## [类的等价比较](https://lingcoder.gitee.io/onjava8/#/book/19-Type-Information?id=%e7%b1%bb%e7%9a%84%e7%ad%89%e4%bb%b7%e6%af%94%e8%be%83) 当你查询类型信息时,需要注意:instanceof 的形式(即`instanceof`或`isInstance()`,这两者产生的结果相同) 和 与 Class 对象直接比较 这两者间存在重要区别。下面的例子展示了这种区别: ~~~ // typeinfo/FamilyVsExactType.java // instanceof 与 class 的差别 // {java typeinfo.FamilyVsExactType} package typeinfo; class Base {} class Derived extends Base {} public class FamilyVsExactType { static void test(Object x) { System.out.println( "Testing x of type " + x.getClass()); System.out.println( "x instanceof Base " + (x instanceof Base)); System.out.println( "x instanceof Derived " + (x instanceof Derived)); System.out.println( "Base.isInstance(x) " + Base.class.isInstance(x)); System.out.println( "Derived.isInstance(x) " + Derived.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))); } public static void main(String[] args) { test(new Base()); test(new Derived()); } } ~~~ 输出结果: ~~~ Testing x of type class typeinfo.Base x instanceof Base true x instanceof Derived false Base.isInstance(x) true Derived.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 Testing x of type class typeinfo.Derived x instanceof Base true x instanceof Derived true Base.isInstance(x) true Derived.isInstance(x) true x.getClass() == Base.class false x.getClass() == Derived.class true x.getClass().equals(Base.class)) false x.getClass().equals(Derived.class)) true ~~~ `test()`方法使用两种形式的`instanceof`对其参数执行类型检查。然后,它获取`Class`引用,并使用`==`和`equals()`测试`Class`对象的相等性。令人放心的是,`instanceof`和`isInstance()`产生的结果相同,`equals()`和`==`产生的结果也相同。但测试本身得出了不同的结论。与类型的概念一致,`instanceof`说的是“你是这个类,还是从这个类派生的类?”。而如果使用`==`比较实际的`Class`对象,则与继承无关 —— 它要么是确切的类型,要么不是。