Anotações Repetidas (Repeating Annotations)

anotacoes-repetidas-(repeating-annotations)

1 Problema antes do Java 8
Não era possível declarar a mesma anotação várias vezes.

Tentativa gerava erro: Duplicate annotation.

2 Solução: @Repeatable
Agora é possível usar anotações múltiplas em um mesmo elemento.

Definindo a anotação repetível:
Usar @Repeatable apontando para um “container” (ex.: @Roles):

@Repeatable(Roles.class)
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE})
public @interface Role {
String value();
}

Container de anotações:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE})
public @interface Roles {
Role[] value();
}

Aplicação prática:
@Role("presidente")
@Role("diretor")
public class RelatorioController { }

3 Recuperando anotações com Reflection
Método getAnnotationsByType facilita acesso:

RelatorioController controller = new RelatorioController();
Role[] annotationsByType = controller.getClass().getAnnotationsByType(Role.class);
Arrays.asList(annotationsByType)
.forEach(a -> System.out.println(a.value()));

Exemplo: ExemploAnotacoesRepetidas.java

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
navigating-blockchain-project-funding-and-regulatory-compliance

Navigating Blockchain Project Funding and Regulatory Compliance

Next Post
announcing-the-general-availability-of-llama-4-maas-on-vertex-ai

Announcing the general availability of Llama 4 MaaS on Vertex AI

Related Posts