6

我正在尝试编写一个自定义格式化程序(用于 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();

我在这里不知所措。

4

2 回答 2

0

您需要注册 JodaDateTime 而不是 DateTime。

play.data.format.Formatters.register(JodaDateTime.class, new AnnotationDateTimeFormatter());
于 2012-06-25T15:29:36.507 回答
0

我的格式化程序也有类似的问题DateTime。我正在从我这里注册Global.onStart格式化程序似乎只是创建Global类并没有触发重新加载。一旦我修改了另一个触发重新加载的文件(如--- (RELOAD) ---控制台输出所示),它就开始工作了。停止和重新启动您的应用程序应该具有相同的效果。

于 2012-07-02T16:11:17.517 回答