使用包含多个共享代码的构造函数的final字段

时间:2016-07-25 09:09:50

标签: java constructor

我需要从字符串中设置一些最终字段(基本上,通过对它们应用一些正则表达式,无所谓)。不同的构造函数以不同的方式获取此String,因此构造函数看起来像这样

 public Foo(File file, Dog dog, ...)
 {
     String importantString;
     //do some stuff to get importantString
     setFinalFieldsFromString(importantString);
 }

显然,这不起作用,因为您无法在构造函数外部设置最终字段。所以我看到两个不太令人满意的解决方案

  • 删除" final"来自田野
  • 复制并粘贴setFinalFieldsFromString
  • 中的代码

有没有更好的方法?

备注:由于共享代码不在构造函数的开头,我不能从另一个构建函数调用。

1 个答案:

答案 0 :(得分:5)

使用将执行最终字段分配的single primary constructor。所有其他构造函数将使用this()来调用那个,例如:

public Foo(File file, Dog dog, ...)
    this(file, dog, getImportantString());
}

getImportantString()是必需的,因为在this()调用之前你不能在构造函数中做任何事情,并且它也需要是静态的,因为它可以从构造函数中工作。

相关问题