Search code examples
spring-bootjunit

how to say this field has email annotation from outside


@NotNull(message = "emailAddress is mandatory")
@NotEmpty(message = "emailAddress cannot be empty")
@Email(message = "Invalid Email")
private String emailAddress;

I just want to know from outside , emailAdress has Email annotation. Is there any way that we can say it is an email annotaion?


Solution

  • You can use reflection for this. The following test passes:

     public class MyTest {
    
        @Test
        public void test() throws NoSuchFieldException {
            HasEmailAddressValidator hasEmailAddressValidator = new HasEmailAddressValidator();
            boolean result = hasEmailAddressValidator.hasEmailAddress(MyClass.class);
    
            assertTrue(result);
        }
    
        @NoArgsConstructor
        static
        class HasEmailAddressValidator {
            public boolean hasEmailAddress(Class<?> clazz) throws NoSuchFieldException {
                return clazz.getDeclaredField("email").isAnnotationPresent(Email.class);
            }
        }
    
        @Data
        static
        class MyClass {
            @Email(message = "this is an email address")
            private String email;
        }
    }