在 DateTimeFormatter 中添加自定义本地化文本,用于新的自定义 TemporalField

Add custom localized text in DateTimeFormatter, for a new custom TemporalField

我创建了一个 CENTURY 字段实现了 java.time.temporal.TemporalField - 这个问题没有关注这个字段的正确实现细节(稍后会处理),我对 DateTimeFormatter 问题感兴趣,如下所述

基本上,该字段获取时间对象的 ChronoField.YEAR 并使用此值计算世纪(计算是在 getFrom(TemporalAccessor temporal) 方法中进行的,考虑到 1 st 世纪是从第 1 年到第 100 年 - 但正如我所说,我们不要过多关注这些细节。

最基本的用法是:

LocalDate.of(2017, 1, 1).get(CENTURY); // 21

在这种情况下 returns 21

该字段也可以用在 DateTimeFormatter:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    .appendPattern("dd/MM/yyyy ")
    .appendValue(CENTURY)
    .toFormatter();

System.out.println(fmt.format(LocalDate.of(2017, 1, 1))); // 01/01/2017 21

上面的输出是:

01/01/2017 21


但我想做的是为此字段使用自定义的本地化文本。如果我创建这样的格式化程序:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    .appendPattern("dd/MM/yyyy ")
    // century text
    .appendText(CENTURY, TextStyle.SHORT)
    // use English locale
    .toFormatter(Locale.ENGLISH);

System.out.println(fmt.format(LocalDate.of(2017, 1, 1))); // 01/01/2017 21

由于我的新 CENTURY 字段没有本地化数据,文本只有它自己的值 21

我正在尝试找到一种方法来为此字段添加自定义本地化字符串,例如,就像在月份和星期几中所做的那样(假设我已经设置了资源包属性文件)。

检查源代码,我发现格式化程序在内部使用 TextPrinterParser,后者又使用 DateTimeTextProvider 来获取本地化字符串,但是其中的 none 类 是 public,不能使用也不能扩展。 API 似乎没有提供为新字段添加自定义本地化字符串的方法。

我只能通过使用反射和 java.lang.reflect.Proxy 来覆盖 TextPrinterParser 的行为来做到这一点,但我想知道是否有更好的方法(不需要所有这些 "magic").

如何做到这一点(如果可能)?


我知道我也可以使用 appendText(TemporalField field, Map<Long,String> textLookup),但这不是 "locale sensitive" 解决方案(尽管它似乎是可用的最佳解决方法)。

这在今天 java.time.* 是不可能的。 DateTimeTextProvider class 旨在可扩展,但在开发过程中被取消了范围。提供可插入的文本提供程序将是对 Java.

的有用增强