instanceof
表达式或类相等表达式 (例如与 String.class
比较) 的 if
-else
语句链。
这种结构通常表明面向对象的设计失败,要求这种基于类型的调度应通过多态方法调用而不是类型测试的显式链来完成。
示例:
double getArea(Shape shape) {
// 警告: 抽象失败。
// 最好在 shape 接口中
// 声明 getArea() 抽象方法,
// 并在每个继承者中实现。
if (shape instanceof Point) {
return 0;
}
if (shape instanceof Circle) {
return Math.PI *
Math.pow(((Circle) shape).radius(), 2);
}
if (shape instanceof Rectangle) {
return ((Rectangle) shape).width() *
((Rectangle) shape).height();
}
throw new IllegalArgumentException();
}
使用下面的复选框来忽略库类中的 instanceof
表达式。