简体   繁体   English

如何使用引发异常的方法初始化最终的静态数据成员

[英]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-catchException 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.

相关问题 使用引发异常的方法在静态块中初始化的最终静态变量 - Final static variable initialized in static block using method that throws exception 如何处理引发检查异常的静态最终字段初始值设定项 - How to handle a static final field initializer that throws checked exception 初始化枚举中的final字段,该枚举中的值是通过引发Exception的方法加载的? - Initializing a final field in an enum, where the value is loaded through a method which throws an Exception? 最终的非静态数据成员 - Final non-static data member 确定哪个方法抛出异常 - Determining which method throws exception 初始化静态最终变量 - Initialize static final variable 如何使用AssertJ验证静态方法引发异常? - How to verify that static method throws an exception using AssertJ? 如何从main方法(或任何方法)中的args []初始化java中的常量,例如“ public static final Integer” - How to initialize constant such as “public static final Integer” in java from args[] in main method (or any) 无法定义私有静态final变量,因为它会抛出异常 - Can't define a private static final variable because it throws an exception 如何在静态类中初始化最终的静态变量? - How can I initialize final static variable in a static class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM