java 中其他注释的自定义注释

Custom annotation from others annotations in java

我在 json 有约会,例如:

{
   "date": "04/22/2022 16:01:01" 
}

和 class:

public class Foo{
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
    private LocalDateTime date;
}

一切正常。

可以在注释中添加@JsonDeserialize@JsonFormat吗?

我正在尝试这样的事情

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE, ElementType.PARAMETER})
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
public @interface MyLocalDateTimeAnnotation{
}

其中 class 可能看起来像这样:

public class Foo{
    @MyLocalDateTimeAnnotation
    private LocalDateTime date;
}

但是没用。

您需要使用@JacksonAnnotationsInside

Meta-annotation (annotations used on other annotations) used for indicating that instead of using target annotation (annotation annotated with this annotation), Jackson should use meta-annotations it has. This can be useful in creating "combo-annotations" by having a container annotation, which needs to be annotated with this annotation as well as all annotations it 'contains'.

示例:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE, ElementType.PARAMETER})
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
@JacksonAnnotationsInside
public @interface MyLocalDateTimeAnnotation {
}

public class Foo{
    @MyLocalDateTimeAnnotation
    private LocalDateTime date;
}