6

There's something I'm not sure to understand when it comes to using Java annotations. Here is an example :

I create a @Log annotation and add some functionality with it (every method annotated with @Log runs some log before executing the method).

Now I'm creating a new @SuperLog annotation like this one :

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Log
public @interface SuperLog {
     ............
}

This @SuperLog must provide all the stuff @Log does, plus some extra stuff specific to @SuperLog.

Unfortunately when I'm executing some methods annotated with @SuperLog, the log specific to @Log doesn't execute.

I don't understand why : the fact @SuperLog is annotated with @Log doesn't mean it "inherits" properties from @Log ? Shouldn't @SuperLog do every thing @Log is supposed to do?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
AntonBoarf
  • 1,239
  • 15
  • 31

2 Answers2

6

As this question outlines, there is no inheritance of annotations.

And beyond that: keep in mind that annotations (mainly) get meaning at runtime because some framework reacts to their presence.

In other words: you could create a framework that somehow supports annotations coming with an inheritance tree. But assuming you are working with some existing framework, you have to accept what this framework is doing.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Thanks but with SpringBootApplication annotation, I noticed it is annotated with ComponentScan, EnableAutoConfiguration etc.. And this SpringBootApplication annotation does provide all services provided by these other annotations. So it does look like there's some "inheritance" – AntonBoarf May 25 '18 at 18:03
  • 1
    @AntonBoarf As said, this depends on what exactly the framework is doing. In other words: when the framework does `instanceof` , then "inheritance" isn't supported. But when the framework "scans" each annotation, it can very well determine such inherited aspects. – GhostCat May 25 '18 at 18:05
  • 1
    So does that mean that when (taking my first example) I annotated my SuperLog annotation with Log annotation, by default it does nothing. I must be in charge of noticing that SuperLog is annotated with Log and implement myself the logic I want, correct ? – AntonBoarf May 25 '18 at 18:09
  • That is the conclusion I would make here, too. – GhostCat May 28 '18 at 19:54
1

I guess you 'execute some methods annotated @SuperLog' means use 'Spring AOP'.

As GhostCat said, the inheritance is depends on framework's implementation. And unfortunately Spring AOP pointcut doesn't support meta-annotation yet.

You can follow this spring improvement.

Dean Xu
  • 4,438
  • 1
  • 17
  • 44