First of all, you need to change annotation retention to RUNTIME (default is CLASS), so they may be read reflectively. Change to like this:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface HolaAn {
String message();
}
You are trying to get annotation from the class, but your annotation are on a field, the only element target. In this example, you are able to get the annotation in this way:
@HolaAn(message = "MUNDO")
private Hola hola;
@Test
public void testMessageOnField() {
final Field[] fields = HolaTest.class.getDeclaredFields();
for (final Field field : fields) {
if (field.isAnnotationPresent(HolaAn.class)) {
final HolaAn annotation = field.getAnnotation(HolaAn.class);
Assert.assertTrue(annotation.message().equals("MUNDO"));
}
}
}
If you need to get the annotation from the class, change it to something like this:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
public @interface HolaAn {
String message();
}
Then, you are able to get annotation message like this:
@HolaAn(message = "CLASS")
public class Hola {
public Hola() {
final String message = this.getClass().getAnnotation(HolaAn.class).message();
System.out.println(message);
}
}
@Test
public void testMessage() {
hola = new Hola();
}
Or:
@Test
public void testMessageSecondWay() {
hola = new Hola();
final Class<?> theClass = hola.getClass();
if (theClass.isAnnotationPresent(HolaAn.class)) {
final HolaAn annotation = theClass.getAnnotation(HolaAn.class);
Assert.assertTrue(annotation.message().equals("CLASS"));
}
}