[英]How To Initialize final static data member with the method which throws Exception
I was Trying to Initialize some of my class's static final
data member. 我正在尝试初始化类的某些
static final
数据成员。
and Here is what I'm trying. 这就是我正在尝试的。
package mypkg;
import java.util.*;
import java.text.SimpleDateFormat;
public class Customer {
...
private static SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
private static final Date DOB_MIN=sdf.parse("1-1-1985");
private static final Date DOB_MAX=sdf.parse("31-12-1995");
...
}
But as I know, .parse()
throws ParseException
which must be Handled. 但据我所知,
.parse()
抛出ParseException
,必须进行处理。
But As you can see you cant use try-catch
or Exception Delegation
there. 但是如您所见,您不能在那里使用
try-catch
或Exception Delegation
。
Also I can't use static initializer block
as those members are final
in nature. 另外,我不能使用
static initializer block
因为这些成员本质上是final
的。
SO 所以
Is there any way to achieve this? 有什么办法可以做到这一点?
In short, 简而言之,
How To Initialize final static data member with the method which throws Exceptio n 如何使用引发异常的方法初始化最终的静态数据成员
Create a static parsing function that delegates to sdf.parse and catches the exception. 创建一个静态解析函数,委派给sdf.parse并捕获异常。
private static SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
private static final Date DOB_MAX = safeParse("31-12-1995");
static Date safeParse(String input) {
try {
return sdf.parse(input);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
The simplest way is to write a method that handles the exception. 最简单的方法是编写一个处理异常的方法。
private static Date parse( String date) {
try {
return sdf.parse( date );
} catch (Exception ex) {
throw new IllegalStateException( "Failed to initialise date "+date, ex );
}
}
However you should be very careful with SimpleDateFormat
, as it's not thread-safe, so sharing the same instance between everyone may not be a good idea. 但是,使用
SimpleDateFormat
应该非常小心,因为它不是线程安全的,因此在每个人之间共享同一实例可能不是一个好主意。 If you only use it to initialise your constants, it's fine but if you plan to use it elsewhere, make sure that sdf.parse()
is only ever called in a synchronized block. 如果仅使用它来初始化常量,那很好,但是如果您打算在其他地方使用它,请确保仅在同步块中调用
sdf.parse()
。
Also I can't use static initializer block as those members are final in nature. 另外,我不能使用静态初始化程序块,因为这些成员本质上是最终的。
Sure you can. 你当然可以。 As long as inside the static block you always either set the field or propagate up an exception.
只要在静态块内,您就始终可以设置字段或传播异常。 There will be no compiler errors.
不会有编译器错误。
This compiles just fine: 这样编译就可以了:
private static SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
private static final Date DOB_MIN;
private static final Date DOB_MAX;
static{
try {
DOB_MIN=sdf.parse("1-1-1985");
DOB_MAX=sdf.parse("31-12-1995");
} catch (ParseException e) {
//handle your exception here.
//could rethrow unchecked exception too
throw new IllegalStateException("invalid dates");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.