Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and @annotations

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?

like image 416
AntonBoarf Avatar asked May 25 '18 17:05

AntonBoarf


People also ask

Can classes be annotated in Java?

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line. As of the Java SE 8 release, annotations can also be applied to the use of types.

What is annotation called in Java?

Java annotations are metadata (data about data) for our program source code. They provide additional information about the program to the compiler but are not part of the program itself. These annotations do not affect the execution of the compiled program. Let's take an example of @Override annotation.

Why annotations are used in Java?

Annotations are used to provide supplemental information about a program. Annotations start with '@'. Annotations do not change the action of a compiled program. Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc.


2 Answers

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.

like image 52
GhostCat Avatar answered Nov 11 '22 23:11

GhostCat


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.

like image 1
Dean Xu Avatar answered Nov 11 '22 23:11

Dean Xu