如何创建一个只能设置一次但在Java中不是最终的变量 [英] How to create a variable that can be set only once but isn't final in Java
问题描述
我想要一个可以使用一个变量unset( id
)创建实例的类,然后稍后初始化此变量,并在初始化后使其不可变即可。实际上,我想要一个 final
变量,我可以在构造函数之外进行初始化。
I want a class that I can create instances of with one variable unset (the id
), then initialise this variable later, and have it immutable after initialisation. Effectively, I'd like a final
variable that I can initialise outside of the constructor.
目前,我使用一个抛出异常
的setter即兴创建,如下所示:
Currently, I'm improvising this with a setter that throws an Exception
as follows:
public class Example {
private long id = 0;
// Constructors and other variables and methods deleted for clarity
public long getId() {
return id;
}
public void setId(long id) throws Exception {
if ( this.id == 0 ) {
this.id = id;
} else {
throw new Exception("Can't change id once set");
}
}
}
这是一个很好的方法吗?谈论我正在做什么?我觉得我应该能够在初始化后设置一些不可变的东西,或者我可以使用一种模式来使它更优雅。
Is this a good way of going about what I'm trying to do? I feel like I should be able to set something as immutable after it's initialised, or that there is a pattern I can use to make this more elegant.
推荐答案
让我建议你更优雅的决定。
第一个变种(不抛出异常):
Let me suggest you a little bit more elegant decision. First variant (without throwing an exception):
public class Example {
private Long id;
// Constructors and other variables and methods deleted for clarity
public long getId() {
return id;
}
public void setId(long id) {
this.id = this.id == null ? id : this.id;
}
}
第二个变种(抛出异常) ):
Second variant (with throwing an exception):
public void setId(long id) {
this.id = this.id == null ? id : throw_();
}
public int throw_() {
throw new RuntimeException("id is already set");
}
这篇关于如何创建一个只能设置一次但在Java中不是最终的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!