Whether the annotation supports inheritance
Inheritance is not supported
You can't use the keyword extends to inherit from an @interface, but annotations are compiled so that the compiler automatically inherits the interface.
Although decompiling reveals that the annotation inherits the Annotation interface, even though Java's interfaces allow for multiple inheritance, it is still not possible to use the extends keyword to inherit @interface when defining annotations.
In contrast to annotation inheritance, an annotated subclass inheriting a parent class annotation can use @Inherited: if a class uses an Annotation that is modified by @Inherited, its subclasses will automatically have that annotation.
Principles of Annotation Implementation
//meta annotations
public @interface annotation name {
}
Customized annotations after decompilation
public interface MyAnno extends {
}
That is, the essence of an annotation is actually an interface and inherits from it.
Therefore, properties in annotations are constants and methods are abstract methods. But custom annotations cannot use void return types. And methods in annotations are generally called "properties" because the usage is generally: method = xxx
The return value type has the following values:
-
fundamental data type
-
String
-
enumeration
-
annotate
-
Arrays of the above types
Runtime Annotation Resolution
After defining an annotation, you can use it in your code, but that's not all, you still need to parse and process the annotation. At runtime, you need to use reflection to parse the annotations, and there are reflection APIs that are specifically designed to handle annotations:
- AnnotatedElement : This is the core type of the reflection interface to deal with annotations, it is the base class of the reflection types Method, Field and Constructor, through its methods to get the annotation Annotation instance.
- Using Annotation for specific annotations
Note that annotations are parsed and processed using reflection, so the annotations should be used when they are defined, otherwise you can't get the annotation information using reflection, because reflection is at runtime (Runtime).
Parsing annotation instances:
public class MethodInfoParsing {
public static void main(String[] args) {
try {
Method[] methods =
.getClassLoader().loadClass("MethodInfoExample").getDeclaredMethods();
for (Method method : methods) {
if (!()) {
continue;
}
for (Annotation annotation : ()) {
("Annotation " + annotation + " on method " + ());
}
MethodInfo info = ();
if ("Paul".equals(())) {
("From Pauls: " + ());
}
}
} catch (ClassNotFoundException e) {
}
}
}
About the Author.
From the front-line programmer Seven's exploration and practice, continuous learning iteration in the~
This article is included in my personal blog:https://
Public number: seven97, welcome to follow~