Search code examples
javaspringannotationsspring-annotations

How to skip an annotation call based on a flag in the same class


I have couple of annotations on a getter as below. I would like to skip all the annotations call on the getter based on a boolean in the same class. Is there any way to do it?

@MyAnnotation1(message = "{someMessage1}")
@MyAnnotation2(message = "{someMessage2}")
public Date getFromDate() {
    return fromDate;
}

Solution

  • You can define another annotation as @Ignore on that field if that annotated field is set you can simply ignore your annotation processing.

       @Ignore
       private boolean value;
    

    You can define your own annotation as

       @Target(ElementType.FIELD)
       @Retention(RetentionPolicy.RUNTIME)
       /**
        * This Annotation should be used on boolean field to set specify whether annotation processing should be        ignored for that class
        */
       public @interface Ignore {
    
       }
    

    Remember this is custom annotation so you will need to write code to handle it

    PS Note: Assuming you are writing custom annotations. And there processing.