Considering the following annotation:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MinhaAnotacao {
String valor();
}
Defined in a class:
@MinhaAnotacao(valor = "algum valor")
class ExemploStackOverflow {
}
I know you can get the value of the valor
field at runtime, OK.
But is it possible to change this value too? For example:
ExemploStackOverflow exemplo = new ExemploStackOverflow();
// Exibe "algum valor"
System.out.println(exemplo.getClass().getAnnotation(MinhaAnotacao.class).valor());
// Chama algum método que altera o conteúdo do campo "valor" da anotação.
AnnotacoesUtils.mudarValor(exemplo, "novo valor");
// Exibiria "novo valor"
System.out.println(exemplo.getClass().getAnnotation(MinhaAnotacao.class).valor());
Is there any way to do this?
I found a possible solution in StackOverflow that seems to be gambiarra. But it does not work in Java version 8, an exception is thrown when calling:
Field field = Class.class.getDeclaredField("annotations");