使用辅助私有方法初始化最终属性

jil*_*t3d 2 java code-reuse final properties

我在带有构造函数的 Java 类中定义了几个最终属性,该类具有初始化属性的所有信息。

public final class A {
   private final Object prop1;
   private final Object prop2;

   public A(Object someObj, String prop1Str, String prop2Str) {
       //initialize prop1 and prop2 based on information provided from someObj, prop1Str and prop2Str parameter (1)
   }
}
Run Code Online (Sandbox Code Playgroud)

我想在 A 类中引入一个具有以下签名和语义的新构造函数

   public A(Object obj1, Object obj2, String prop1Str, String prop2Str) {
       //use obj1 and obj2 to initialize the someObj
       //initialize prop1 and prop2 based on information provided from someObj, prop1Str and prop2Str parameter (1)
   }
Run Code Online (Sandbox Code Playgroud)

如何重用 (1) 中的代码?我尝试使用辅助私有方法,但 Java6 给了我一个编译错误,因为该类的属性是最终的,并且它们可能尚未初始化。

编辑:请注意,我无法从第一行中的第二个构造函数调用第一个构造函数,因为首先我需要进行一些计算,然后重用有问题的代码。

Aar*_*lla 5

你发现了一个缺点final:-)

Java 必须确保final构造函数完成时所有字段都已初始化。由于各种其他限制,这意味着必须在构造函数的代码块内分配字段。

解决方法:

  1. 使用static辅助方法(根据设计,这些方法不依赖于类的状态,因此不依赖于任何final字段)。

  2. 使用构建器模式(将所有参数放入辅助类中,该类具有build()返回所需结果的方法)。

  3. 不要使用final. 您可以通过省略 setter 来获得相同的事件。如果您担心类中的代码可能会更改字段,请将它们移至新的基类。