2

How can I combine annotations in Java?

EDIT I was asking if I two annotations a and b, can I combine to a single annotations c? If possible, how do I do that?

javaguy
  • 4,404
  • 10
  • 32
  • 35
  • 5
    You're going to need to add more details. What exactly do you mean by combine them? Do you mean how do you add an annotation to an annotation? – Matt H Aug 08 '10 at 21:50

2 Answers2

6

You cannot combine the annotations by e.g. annotating the annotations, unless the annotation consumer will process the meta-annotation tree explicitly. For example, Spring supports such feature for @Transactional, @Component and some other annotations (you may wish to have a look at SpringTransactionAnnotationParser#parseTransactionAnnotation()). Nice to have this feature in Java core, but alas...

However you can declare the common parent class that has a set of annotations you need and extend it. But this is not always applicable.

Community
  • 1
  • 1
dma_k
  • 10,431
  • 16
  • 76
  • 128
  • True, I tried annotating @ SimulationEntity with @ Entity, but it didn't work, JPA won't recognize @ Entity as meta-annotation. – Ivan Matavulj Sep 28 '18 at 14:14
2

Assuming you want to have multiple annotations on a single element, you can just list them in sequence.

The Wikipedia page on Java annotations has quite a few useful examples, e.g.

  @Entity                      // Declares this an entity bean
  @Table(name = "people")      // Maps the bean to SQL table "people"
  class Person implements Serializable {
     ...
  }
mikera
  • 105,238
  • 25
  • 256
  • 415