为什么要在静态块中初始化最终的静态变量?例如public static final Object o;静态{o = new ...}

时间:2015-04-17 13:25:13

标签: java static immutability api-design

编写第一个更冗长的版本而不是后一个版本的优势是什么?

public static final DateTimeFormatter ISO_LOCAL_DATE;
static {
    ISO_LOCAL_DATE = new DateTimeFormatterBuilder()
            .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
            .appendLiteral('-')
            .appendValue(MONTH_OF_YEAR, 2)
            .appendLiteral('-')
            .appendValue(DAY_OF_MONTH, 2)
            .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
}

而不是简单地写

public static final DateTimeFormatter ISO_LOCAL_DATE2 = new DateTimeFormatterBuilder()
        .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
        .appendLiteral('-')
        .appendValue(MONTH_OF_YEAR, 2)
        .appendLiteral('-')
        .appendValue(DAY_OF_MONTH, 2)
        .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);

第一种样式用于Java API,例如在java.time.format.DateTimeFormatter

0 个答案:

没有答案