在构造函数中使用 "this instanceof …" 或 "getClass()" 是否安全?

Is it safe to use "this instanceof …" or "getClass()" in a constructor?

Java 语言是否保证 instanceof 运算符或 getClass() 应用于构造函数中 this 的方法始终适用于更深层次的 class在层次结构中?

例如,如果我想限制允许从超级class调用构造函数的子class,我可以这样做:

class A {
  A() {
    final Class<?> clazz = getClass();
    if (clazz != A.class && clazz != B.class && clazz != C.class) {
      throw new IllegalStateException();
    }
  }
}

但我想知道语言是否保证它会工作。

是的,有保证。

如果您没有显式指定,则始终会隐式调用 super() 作为构造函数的第一个操作。 (JLS)

强制执行此约束的原因 - 而不是允许在任何时候调用父构造函数 - 是为了保证所有超级 类 都被初始化,无论是 Object,或任何其他超级类型。 Object 的每个实例方法此时都可以安全使用; getClass也不例外。

另见 Why do this() and super() have to be the first statement in a constructor?

您的问题本质上是,在哪个对象上调用 getClass JLS覆盖如下

The keyword this may be used only in the following contexts:

  • the body of a constructor of a class (§8.8.7)
  • ...

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method or default method was invoked (§15.12), or to the object being constructed.