Can#39;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
的事实,因为它是 最终
.
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
.
但是,需要向静态初始化程序添加复杂的初始化逻辑和异常处理通常表明存在更基本的设计问题.您在评论部分写道,这是一个数据库连接池类.而不是使用 static 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.
这篇关于无法定义私有静态最终变量,因为它会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法定义私有静态最终变量,因为它会引发异常
基础教程推荐
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01