java在构造函数中使用“this instanceof…”或“getClass()”安全吗?
Java语言是否保证instanceof
运算符或应用于构造函数中this
的getClass()
方法始终应用于层次结构中的较深类
例如,如果我想限制允许从超类调用构造函数的子类,我可以这样做:
class A {
A() {
final Class<?> clazz = getClass();
if (clazz != A.class && clazz != B.class && clazz != C.class) {
throw new IllegalStateException();
}
}
}
但我想知道这种语言是否能保证它会起作用
# 1 楼答案
是的,有保证
如果未显式指定
super()
,则构造函数的第一个操作总是隐式调用super()
。(JLS)强制执行此约束的原因—而不是允许在任何点调用父构造函数—是为了确保所有超类都被初始化,无论是
Object
还是任何其他超类型。此时Object
的每个实例方法都可以安全使用getClass
也不例外另见Why do this() and super() have to be the first statement in a constructor?
# 2 楼答案
您的问题本质上是,在哪个对象上调用
getClass
JLS将其涵盖如下