Search code examples
javahibernate-validator

Determine whether field is annotated with a given annotations


I don't know if you managed to figure out what i am trying to do just from the title so I'll try to explain with example

Lets suppose I have created my own annotation @VerifySomething

And I have created test class for that annotation to make sure it works.

Now lets suppose that I have class SomeClass with field something anoted with annotation @VerifySomething

class SomeClass {
    @VerifySomething
    String something;
}

So far so good, but now I want to create test class for my SomeClass however I don't see any point in verifying all the test cases of something as I have already checked that @VerifySomething works as it should in class which tests that annotation, however I need to make sure that field something actually has @VerifySomething annotation without copy pasting all these test cases.

So my question is, is there a way to check if some field has one or more required annotation without writing test cases I have already written in annotation test class to make sure it works as it should.


Solution

  • You can use getAnnotation (docs) to determine if there is a specific Annotation on the field, which takes the annotation class as a parameter:

    field.getAnnotation( SomeAnnotation.class );
    

    Here is a method you can use to verify that a class has a field annotated by given annotation:

    import java.lang.reflect.Field;
    import javax.validation.constraints.NotNull;
    import org.junit.Test;
    import org.springframework.util.Assert;
    
    public class TestHasAnnotatedField {
        @Test
        public void testHasFieldsWithAnnotation() throws SecurityException, NoSuchFieldException {
            Class<?>[] classesToVerify = new Class[] {MyClass1.class, MyClass2.class};
            for (Class<?> clazz : classesToVerify) {
                Field field = clazz.getDeclaredField("something");
                Assert.notNull(field.getAnnotation(NotNull.class));
            }
        }
        static class MyClass1 { @NotNull String something; }
        static class MyClass2 { @NotNull String something; }
    }