我已经阅读了迄今为止发布的所有答案,但还没有找到满意的答案。回答此检查是否有某种声明?instanceof
或者我应该使用qux.getClass().equals(Foo.class)
我会说是的问题,instanceof
java中有运算符来检查对象是否是类的实例。下面是一个例子-:
class Vehicle {
}
class Car extends Vehicle {
}
public class Research {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
if (vehicle instanceof Vehicle) {
System.out.println("vehicle instanceof Vehicle : TRUE");
} else {
System.out.println("vehicle instanceof Vehicle : FALSE");
}
if (vehicle instanceof Car) {
System.out.println("vehicle instanceof Car : TRUE");
} else {
System.out.println("vehicle instanceof Car : FALSE");
}
System.out.println();
Car car = new Car();
if (car instanceof Vehicle) {
System.out.println("car instanceof Vehicle : TRUE");
} else {
System.out.println("car instanceof Vehicle : FALSE");
}
if (car instanceof Car) {
System.out.println("car instanceof Car : TRUE");
} else {
System.out.println("car instanceof Car : FALSE");
}
}
}
输出-:
vehicle instanceof Vehicle : TRUE
vehicle instanceof Car : FALSE
car instanceof Vehicle : TRUE
car instanceof Car : TRUE
描述-:instanceof
运算符告诉对象是类的实例还是它的父类(直到任何级别)。
vehicle instanceof Car : FALSE
输出行表明instanceof
运算符不会判断对象是否是其子类的实例。
另一种方法是用来getClass().equals(Foo.class)
确定一个对象是否是一个类的实例。让我们看看下面的例子-:
class Vehicle {
}
class Car extends Vehicle {
}
public class Research {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
if (vehicle.getClass().equals(Vehicle.class)) {
System.out.println("vehicle instanceof Vehicle : TRUE");
} else {
System.out.println("vehicle instanceof Vehicle : FALSE");
}
if (vehicle.getClass().equals(Car.class)) {
System.out.println("vehicle instanceof Car : TRUE");
} else {
System.out.println("vehicle instanceof Car : FALSE");
}
System.out.println();
Car car = new Car();
if (car.getClass().equals(Vehicle.class)) {
System.out.println("car instanceof Vehicle : TRUE");
} else {
System.out.println("car instanceof Vehicle : FALSE");
}
if (car.getClass().equals(Car.class)) {
System.out.println("car instanceof Car : TRUE");
} else {
System.out.println("car instanceof Car : FALSE");
}
}
}
输出-:
vehicle instanceof Vehicle : TRUE
vehicle instanceof Car : FALSE
car instanceof Vehicle : FALSE
car instanceof Car : TRUE
描述-:从上面的示例中可以清楚地看出,应该在哪里选择哪一个(以上两个)?
重要笔记-:
instanceof
NullPointerException
如果引用变量未指向任何对象(即其具有空引用),则运算符不会抛出异常。
car.getClass().equals(Car.class)
NullPointerException
如果car
没有指向任何对象(即它具有空引用),将抛出异常。因此,必须对此进行额外的空检查,例如car != null && car.getClass().equals(Car.class)
以防止NullPointerException
.
instanceof
运算符告诉对象是类的实例还是它的父类(直到任何级别)。
car.getClass().equals(Car.class)
将判断一个对象是否只是类的一个实例。(根本不考虑父类和子类)