在Java中初始化最终变量的问题 [英] Problems initializing a final variable in Java
问题描述
我继续遇到Java中的一个问题的轻微变化,它开始得到我,我不能真正想到一个正确的方法来解决它。
我有一个object属性是final,但是是动态的。也就是说,我希望该值在分配后保持不变,但每个运行时的值可能不同。所以我在类的开始处声明类级别的变量 - 例如
private final FILE_NAME;
。然后,在构造函数中,我给它赋值 - 说 FILE_NAME = buildFileName();
问题开始当我在引发异常的 buildFileName()
方法中有代码时。所以我在构造函数中尝试这样的东西:
try {
FILE_NAME = buildFileName();
}
catch(异常e){
...
System.exit(1);
}
现在我有一个错误 - 空白的最后一个字段FILE_NAME可能没有初始化。这是我开始对Java的严格编译器有点恼火的地方。我知道这不会是一个问题,因为如果它捕获程序将退出...但编译器不知道,所以不允许这个代码。如果我尝试添加一个虚拟作业到catch,我得到 - 最后一个字段FILE_NAME可能已被分配。我显然无法在try-catch之前分配默认值,因为我只能分配一次。
任何想法...?
第二个想法,我想我刚刚想出了一个解决方案! - 使用一个中间变量。
String fileName = null;
try {
fileName = buildFileName();
}
catch(异常e){
...
System.exit(1);
}
FILE_NAME = fileName;
不知道为什么花了我这么久才想到这个...
I keep running into slight variations of a problem in Java and it's starting to get to me, and I can't really think of a proper way to get around it.
I have an object property that is final, but dynamic. That is, I want the value to be constant once assigned, but the value can be different each runtime. So I declare the class level variable at the beginning of the class - say private final FILE_NAME;
. Then, in the constructor, I assign it a value - say FILE_NAME = buildFileName();
The problem begins when I have code in the buildFileName()
method that throws an exception. So I try something like this in the constructor:
try{
FILE_NAME = buildFileName();
}
catch(Exception e){
...
System.exit(1);
}
Now I have an error - "The blank final field FILE_NAME may not have been initialized." This is where I start to get slightly annoyed at Java's strict compiler. I know that this won't be a problem because if it gets to the catch the program will exit... But the compiler doesn't know that and so doesn't allow this code. If I try to add a dummy assignment to the catch, I get - "The final field FILE_NAME may already have been assigned." I clearly can't assign a default value before the try-catch because I can only assign to it once.
Any ideas...?
On second thought, I think I just came up with a solution! - use an intermediate variable.
String fileName = null;
try{
fileName = buildFileName();
}
catch(Exception e){
...
System.exit(1);
}
FILE_NAME = fileName;
Don't know why it took me so long to think of this...
这篇关于在Java中初始化最终变量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!