简体   繁体   中英

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.

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.

But As you can see you cant use try-catch or Exception Delegation there.

Also I can't use static initializer block as those members are final in nature.

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.

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. 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.

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM