无法定义私有静态final变量,因为它会抛出异常 [英] Can't define a private static final variable because it throws an exception
问题描述
我有一个类如下:
public class SomeClassImpl implements SomeClass {
private static final SomeLib someLib = new SomeLib();
}
我不能这样做,因为SomeLib会抛出一个UnknownHostException。
I can't do this because SomeLib throws a UnknownHostException.
我知道我可以将实例化移动到构造函数中,但有没有办法按照我上面的方式以某种方式执行它?这样我就可以将var标记为final。
I know I could move the instantiation to the constructor, but is there a way for me to do it the way I have it above somehow? That way I can keep the var marked as final.
我试图寻找如何在类级别抛出异常但却找不到任何内容。
I tried to look for how to throw exceptions at the class level but can't find anything on it.
推荐答案
您可以使用静态初始值设定项:
You can use static initializer:
public class SomeClassImpl implements SomeClass {
private static final SomeLib someLib;
static {
SomeLib tmp = null;
try {
tmp = new SomeLib();
} catch (UnknownHostException uhe) {
// Handle exception.
}
someLib = tmp;
}
}
注意我们需要使用临时变量来避免变量someLib可能尚未初始化错误并且应对我们只能分配 someLib
的事实,因为它是 final
。
Note that we need to use a temporary variable to avoid "variable someLib might not have been initialized" error and to cope with the fact that we can only assign someLib
once due to it being final
.
但是,需要向静态初始化程序添加复杂的初始化逻辑和异常处理通常是更基本的设计问题的标志。您在评论部分写道,这是一个数据库连接池类。而不是使用静态最终考虑使其成为实例变量。然后,您可以在构造函数中进行初始化,或者更好地在静态工厂方法中进行初始化。
However, the need to add complex initialization logic and exception handling to static initializer is often a sign of a more fundamental design issue. You wrote in the comments section that this is a database connection pool class. Instead of using static final consider making it an instance variable. You can then do the initialization in a constructor or better yet in a static factory method.
这篇关于无法定义私有静态final变量,因为它会抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!