有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在构造函数中使用“this instanceof…”或“getClass()”安全吗?

Java语言是否保证instanceof运算符或应用于构造函数中thisgetClass()方法始终应用于层次结构中的较深类

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

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

但我想知道这种语言是否能保证它会起作用


共 (2) 个答案

  1. # 1 楼答案

    是的,有保证

    如果未显式指定super(),则构造函数的第一个操作总是隐式调用super()。(JLS

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

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

  2. # 2 楼答案

    您的问题本质上是,在哪个对象上调用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.