简体   繁体   English

确保使用Java初始化final字段

[英]Making sure a final field is initialized in Java

I extend a class with multiple constructors. 我用多个构造函数扩展了一个类。 I add a final field in my subclass which ofcourse needs to be initialized in my own constructors. 我在子类中添加了一个final字段,这当然需要在自己的构造函数中进行初始化。

The problem is I don't want to re-implement (most) of the constructors of the superclass, so I would like to do something like this: 问题是我不想重新实现(大多数)超类的构造函数,所以我想做这样的事情:

public myConstructor(Object... params){
    super(params);
    try{
        this.finalField = "backup value";
    }
    catch(someException e){

    }
}

Is this possible in some way or the other? 这有可能以其他方式出现吗?

edit : I realized this scenario will never happen, because the superclass constructor will never call my own constructor. 编辑 :我意识到这种情况永远不会发生,因为超类构造函数永远不会调用我自己的构造函数。

To simplify process of object initialization, usually I use the following solutions: 为了简化对象初始化的过程,通常我使用以下解决方案:

  • You could create a static-factory method which will be create object (and throw exceptions if needed) instead of constructors and provide common initialization functionality in reusable private method. 您可以创建一个静态工厂方法,该方法将创建对象(并在需要时引发异常)而不是构造函数,并在可重用的私有方法中提供常见的初始化功能。
  • Also you could use Builder-pattern instead of multiple constructors. 您也可以使用Builder模式而不是多个构造函数。 http://en.wikipedia.org/wiki/Builder_pattern http://en.wikipedia.org/wiki/Builder_pattern

让所有构造函数都调用一个用于设置final字段的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM