无法定义私有静态最终变量,因为它会引发异常

2022-01-19 00:00:00 initialization exception java

我有这样的课:

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.

相关文章