gpt4 book ai didi

java - 在 super 构造函数运行之前初始化字段?

转载 作者:IT老高 更新时间:2023-10-28 20:53:48 25 4
gpt4 key购买 nike

在Java中,有没有办法在 super 构造函数运行之前初始化一个字段?

即使是我能想到的最丑陋的 hack 也会被编译器拒绝:

class Base
{
Base(String someParameter)
{
System.out.println(this);
}
}

class Derived extends Base
{
private final int a;

Derived(String someParameter)
{
super(hack(someParameter, a = getValueFromDataBase()));
}

private static String hack(String returnValue, int ignored)
{
return returnValue;
}

public String toString()
{
return "a has value " + a;
}
}

注意:当我从继承切换到委托(delegate)时,问题就消失了,但我仍然想知道。

最佳答案

不,没有办法做到这一点。

根据language specs , 实例变量甚至在调用 super() 之前都不会被初始化。

这些是在类实例创建的构造函数步骤中执行的步骤,取自链接:

  1. Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.
  2. If this constructor begins with an explicit constructor invocation (§8.8.7.1) of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.
  3. This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.
  4. Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.
  5. Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.

关于java - 在 super 构造函数运行之前初始化字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15682457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com