Determine if a field with given annotations is annotated

I don’t know if you managed to figure out what I’m trying to do only from the name, so I’ll try to explain using an example

Suppose I created my own @VerifySomething annotation

And I created a test class for this annotation to make sure it works.

Now let's assume that I have a class SomeClass with a field something with annotation @VerifySomething

 class SomeClass { @VerifySomething String something; } 

So far it’s so good, but now I want to create a test class for my SomeClass , however I don’t see the point of checking all test cases of anything, as I already checked that @VerifySomething works as it should in a class that checks this annotation, however, I need to make sure that something in the field really has the @VerifySomething annotation without copying pasting all of these test cases.

So my question is, is there a way to check if any field has one or more required annotations without writing test cases, which I already wrote in the annotation test class to make sure that it works as it should.

+8
java hibernate-validator
source share
2 answers

You can use getAnnotation to determine if there is a specific annotation in a field that takes an annotation class as a parameter:

 field.getAnnotation( SomeAnnotation.class ); 

Here is a method you can use to verify that the class has a field annotated with the specified 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; } } 
+11
source share

I'm not sure what to follow, but if you want to check if the class and its properties have the specified Bean Validation restriction, you can use the api metadata. 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. Using theDescriptor # getConstraintDescriptors () property, you get a set of ConstraintDescriptors, which you can repeat to make sure that the annotation for the constraint has been used.

Please note that this is a special Bean Validation solution compared to the general reflection, as in the answer above, but it depends on what you really are. Honestly, I still do not quite understand your use case.

+2
source share

All Articles