Search code examples
javainheritanceannotations

How to do inheritance @JsonFormat annotation in java?


I am working on JPA-Hibernate project. I have a date deserilaze problem but i have also solution in the below.

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.S")
private Date createdAt;

When I use @JsonFormat annotation with date, i solved the problem but i don't want to use this annotation every Date variable. I want to use MyDate annotation, as you can see below.

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.fasterxml.jackson.annotation.JsonFormat;

@Inherited
@Target({ ElementType.ANNOTATION_TYPE, ElementType.FIELD,  ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.S")
public @interface MyDate {

}

When i use @MyDate annotation, it doesn't work correctly. I keep failing like I've never used it. What is my mistake?


Solution

  • Here is what you need:

    The usage:

    @MyDate    
    private Date createdAt;
    

    And the MyDate custom annotation class:

    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
    import com.fasterxml.jackson.annotation.JsonFormat;
    
    @JacksonAnnotationsInside
    @Retention(RetentionPolicy.RUNTIME)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.S")
    public @interface MyDate {}