我正在尝试编写一个自定义格式化程序(用于 DateTime 字段,而不是 java.util.Date 字段),但很难让它工作。我已经创建了注释,并扩展了 AnnotationFormatter 类。我在应用程序加载时调用 play.data.format.Formatters.register(DateTime.class, new MyDateTimeAnnotationFormatter()) ,但解析和打印方法永远不会触发。
我该怎么做?
编辑:有问题的代码可能会有所帮助;)
注释类(很大程度上受到 Play Framework 中包含的注释类的启发):
@Target({ FIELD })
@Retention(RUNTIME)
@play.data.Form.Display(name = "format.datetime", attributes = { "pattern" })
public static @interface JodaDateTime {
String pattern();
}
自定义格式化程序类:
public static class AnnotationDateTimeFormatter extends AnnotationFormatter<JodaDateTime, DateTime> {
@Override
public DateTime parse(JodaDateTime annotation, String text, Locale locale) throws ParseException {
if (text == null || text.trim().isEmpty()) {
return null;
}
return DateTimeFormat.forPattern(annotation.pattern()).withLocale(locale).parseDateTime(text);
}
@Override
public String print(JodaDateTime annotation, DateTime value, Locale locale) {
if (value == null) {
return null;
}
return value.toString(annotation.pattern(), locale);
}
为了向框架注册格式化程序,我在 Application 类的静态初始化程序中进行了此调用(可能有更好的放置位置,请随时告诉我在哪里):
play.data.format.Formatters.register(DateTime.class, new AnnotationDateTimeFormatter());
我已经通过调试器单步执行了这个调用并且没有抛出任何错误,但是尽管像这样适当地注释了 DateTime 字段,格式化程序仍然没有运行:
@Formats.JodaDateTime(pattern = "dd.MM.yyyy HH:mm:ss")
public DateTime timeOfRequest = new DateTime();
我在这里不知所措。