Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

java - Can't define a private static final variable because it throws an exception

I have a class like:

public class SomeClassImpl implements SomeClass {
   private static final SomeLib someLib = new SomeLib();
}

I can't do this because SomeLib throws a UnknownHostException.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
   }
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...