要检查对象是否为特定类型的(class或interface输入),你可以使用instanceof运算符。该instanceof运算符仅用于对象引用变量。x instanceof y可以理解为x是-一个y。
的instanceof返回true,如果被测试的引用变量是类型被进行比较。true如果所比较的对象的分配与右侧的类型兼容,它将仍然返回。
对于interface类型,如果任何对象的超类实现了接口,则称该对象为特定interface类型(意味着它将通过instanceof测试)。
package org.nhooo.example.fundamental; public class InstanceofDemo { public static void main(String[] args) { Body body = new Body(); Hand hand = new Hand(); Nail nail = new Nail(); Shoes shoe = new Shoes(); if (body instanceof Man) { System.out.println("body is a Man"); } if (hand instanceof Man) { System.out.println("hand is a Man too"); } if (hand instanceof Body) { System.out.println("hand is a Body"); } // 它应该返回false if (hand instanceof Nail) { System.out.println("hand is a Nail"); } else { System.out.println("hand is not a Nail"); } if (nail instanceof Man) { System.out.println("nail is a Man too"); } if (nail instanceof Hand) { System.out.println("nail is a Hand"); } if (nail instanceof Body) { System.out.println("nail is a Body too"); } // 它应该返回false,因为Shoes不是工具Man if (shoe instanceof Man) { System.out.println("shoe is a Man"); } else { System.out.println("shoe is not a Man"); } //编译错误。不能测试不同的班级 // 类层次结构。 // //if(shoe instanceof Body){ //} } } interface Man { } class Body implements Man { } // 间接实现人 class Hand extends Body { } // 间接实现人 class Nail extends Hand { } class Shoes { }
上面的代码片段的结果:
body is a Man hand is a Man too hand is a Body hand is not a Nail nail is a Man too nail is a Hand nail is a Body too shoe is not a Man