We’ve a public static util method which can parse a string and return a Date object, but it also throws ParseException in case the string parsed cannot be converted to a Date object.
Now, in another class I would like to have a static final Date initialized to a value using the util method described above. But given that the util method throws ParseException, this is not allowed.
This is what I want to do, which is not allowed
public static final MY_DATE = Util.getDateFromString('20000101');
What is the recommended way to keep this Date field ‘final’?
Well you could use a static initializer block:
However, I would advise against this.
Dateis a mutable type – exposing it via a public static final variable is a bad idea.As of Java 8, the
java.timepackage is the most appropriate to use for almost all date/time work, where you’d write:Prior to Java 8, I’d recommend that you use Joda Time which has many immutable date/time types – and is a thoroughly better library for working with dates and times. It looks like you’d want:
Note that even if you do decide to go with
java.util.Date, it doesn’t make much sense to parse the string in my view – you know the values numerically, so why not just supply them that way? If you haven’t got a suitable method to construct aDatefrom a year / month / day (presumably applying an appropriate time zone) then you could easily write one.