Reputation: 153
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.
Upvotes: 15
Views: 23982
Reputation: 796
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; }
}
Upvotes: 24
Reputation: 19129
I am not sure I am following, but in case you want to verify whether a class and or its properties have a given Bean Validation constraint, you can use the meta data api. The entry point is Validator#getConstraintsForClass(SomeClass.class). You get a BeanDescriptor. From there you can do _beanDescriptor#getConstraintsForProperty("something") which gives you a PropertyDescriptor. Via propertyDescriptor#getConstraintDescriptors() you get then a set of ConstraintDescriptors which you can iterate to verify that a given constraint annotation was used.
Note, this is a Bean Validation specific solution compared to generic reflection as in the answer above, but it depends what you are really after. To be honest I don't quite understand your use case yet.
Upvotes: 3