I'm working in one logic, but i dont know if it is possible to do it, i want to use annotation for this, so this is my code
public class Hola {
public JSONConverter() {
String message= getClass().getAnnotation(HolaAn.class).getMessage();
}
}
@Target({ElementType.FIELD})
public @interface HolaAn{
String getMessage();
}
public class MessageTest{
@HolaAn(getMessage= "MUNDO")
private Hola hola;
@Test
public void testMessage(){
hola= new Hola();
}
}
But i have nullPointerException, i dont know very well how to work with my own annotation, any one can said me if this is possible and how to do it?
Best Solution
First of all, you need to change annotation retention to
RUNTIME
(default isCLASS
), so they may be read reflectively. Change to like this: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:
If you need to get the annotation from the class, change it to something like this:
Then, you are able to get annotation message like this:
Or: