On Java custom annotations and obtaining annotations by reflection at runtime

Java custom annotation

Java annotation is some meta information attached to the code, which is used for parsing and using some tools during compilation and runtime, and plays the function of description and configuration.

Annotations do not and cannot affect the actual logic of the code, but only play an auxiliary role. Included in Java Lang.annotation package.

1. Meta annotation

Meta annotation refers to the annotation of annotation. Including @ retention @ target @ document @ inherited.

1.1 @ retention: defines the retention policy for annotations

Annotation class:

Entity class:

Get the help class of the annotation:

To get the annotation at runtime, first create a base class:

Create a subclass to inherit the base class:

Test class:

////////////////////////////////////////////////////////////////////////////////////////////////////////

1. How annotation works:

JDK5. 0 provides the function of annotation, allowing developers to define and use their own annotation types. This function consists of a syntax for defining annotation types, a syntax for describing an annotation declaration, an API for reading annotations, a class file decorated with annotations, and an annotation processing tool.

Annotation does not directly affect the semantics of the code, but it can be regarded as a tool or class library of the program. This in turn affects the semantics of the running program.

Annotations can be read from source files, class files, or through reflection mechanisms at runtime.

2. @ override annotation:

java. lang

The annotation type override @ target (value = method) @ retention (value = source) public @ interface override indicates that a method declaration intends to override another method declaration in the superclass. If the method is annotated with this annotation type but does not override the superclass method, the compiler generates an error message.

@The override annotation indicates that the subclass wants to override the corresponding method of the parent class.

Override is a marker annotation used to identify the annotation. The annotation name itself represents the information to be given to the tool program.

The following is an example of using the @ override annotation:

3. @ deprecated annotation:

java. Lang annotation type: deprecated @ documented @ retention (value = runtime)

Public @ interface deprecated is a program element annotated with @ deprecated. Programmers are not encouraged to use such an element, usually because it is dangerous or there are better choices. The compiler issues warnings when using deprecated program elements or when performing rewriting in deprecated code.

@Deprecated annotation representations are not recommended.

Deprecated is a marker annotation.

The following is an example of using @ deprecated annotation:

4. @ suppresswarnings annotation:

java. Lang annotation type suppresswarnings @ target (value = {type, field, method, parameter, constructor, local_variable}) @ retention (value = source)

Public @ interface suppresswarnings indicates that the comment element should be (and all program elements contained in the comment element). Note that the set of warnings that are unplayed in a given element is a superset of warnings that are unplayed in all containing elements. For example, if you annotate a class to unplay a warning and annotate a method to unplay another warning, this method will be used Both warnings are suppressed in.

Depending on the style, programmers should always use this annotation on the innermost nested elements, where it is effective. If you want to suppress a warning in a particular method, you should annotate the method instead of its class.

@The suppresswarnings annotation indicates that warnings are suppressed.

The following is an example of using the @ suppresswarnings annotation:

5. Custom annotation:

When you use @ interface to customize annotations, you automatically inherit Java lang.annotation. Annotation interface, and other details are automatically completed by the compiler. When defining annotations, you cannot inherit other annotations or interfaces.

Customize the simplest annotation:

5.1. Add variables:

When the attribute name used in the annotation is value, the attribute value interface can be written directly without specifying the attribute name; Variable names other than value need to be assigned in the way of name = value.

5.2. Add default value:

5.3. Multivariable use enumeration:

Use custom annotations:

5.4. Array variables:

Use custom annotations:

6. Set the scope of annotation:

@Documented @Retention(value=RUNTIME) @Target(value=ANNOTATION_TYPE)

Public @ interface retention indicates how long annotation of annotation type will be retained. If there is no retention annotation in the annotation type declaration, the retention policy defaults to retentionpolicy CLASS。

The target meta annotation is valid only if the meta annotation type is used directly for annotation. A meta annotation type is not valid if it is used as a member of another annotation type.

Public enum retentionpolicy extends enum < retentionpolicy > comment retention policy. Constants of this enumeration type describe different strategies for retaining annotations. They are used with the retention meta annotation type to specify how long annotations are retained.

The class compiler will record comments in the class file, but the VM does not need to keep comments at run time.

The runtime compiler will record the comments in the class file, and the VM will keep the comments at run time, so they can be read reflexively.

Source comments to be discarded by the compiler@ The retention annotation can provide the compiler with a retention policy for annotations when defining annotations.

The annotation belonging to the class retention policy has @ suppresswarnings, and the annotation information will not be stored in Class file.

6.1. Use examples in user-defined annotations:

7. An example of reading annotation information of a runtime retention policy using reflection:

java. lang.reflect

Interface annotatedelement

All known implementation classes:

Accessibleobject, class, constructor, field, method, package represents an annotated element of the program currently running in this VM. This interface allows reflective reading of comments. All comments returned by methods in this interface are immutable and serializable. The caller can modify the array returned by the accessor of the assigned array enumeration member; This has no effect on the arrays returned by other callers.

If the annotation returned by the method in this interface (directly or indirectly) contains an assigned class member that references a class that is not accessible in this VM, attempting to read the class by calling the method returned by the relevant class on the returned annotation will result in a typenotpresentexception.

Isannotationpresent Boolean isannotationpresent (class annotationclass) returns true if the annotation of the specified type exists on this element; otherwise, returns false. This method is mainly designed to facilitate access to tag annotations.

Parameters:

Annotationclass - the class object corresponding to the annotation type

return:

Returns true if the annotation of the specified annotation type exists on this object; otherwise, returns false

Throw:

NullPointerException - if the given annotation class is null

Start with the following version:

one point five

Getannotation < T extensions annotation > t getannotation (class < T > annotationclass) if there are comments of the specified type of the element, these comments will be returned; otherwise, null will be returned.

Parameters:

Annotationclass - the class object corresponding to the annotation type

return:

If the comments of the specified comment type of the element exist on this object, these comments are returned, otherwise null is returned

Throw:

NullPointerException - if the given annotation class is null

Start with the following version:

one point five

Getannotations annotation [] getannotations() returns all comments that exist on this element. (if this element has no comments, an array of zero length is returned.) the caller of this method can modify the returned array at will; this will not have any impact on the arrays returned by other callers.

return:

All comments that exist on this element

Start with the following version:

one point five

Getdeclaraedannotations annotation [] getdeclaraedannotations() returns all annotations that exist directly on this element. Unlike other methods in this interface, this method ignores inherited comments. (if no comments exist directly on this element, an array of zero length is returned.) the caller of this method can modify the returned array at will; this will not have any impact on the arrays returned by other callers.

return:

All comments that exist directly on this element

Start with the following version:

one point five

The following is an example of reading the annotation information of the runtime retention policy using reflection:

Custom annotation:

Use custom annotations:

Read the information in the annotation:

8. Limiting the use of annotations:

Qualify annotations to use @ target.

@Documented @Retention(value=RUNTIME) @Target(value=ANNOTATION_TYPE)

Public @ interface target indicates the type of program element to which the annotation type applies. If the target meta annotation does not exist in the annotation type declaration, the declared type can be used on any program element. If such meta annotations exist, the compiler enforces the specified usage restrictions. For example, this meta annotation indicates that the declaration type is itself, that is, the meta annotation type. It can only be used on annotation type declarations:

This meta comment indicates that the declaration type can only be used as a member type in a complex annotation type declaration. It cannot be used directly for comments:

This is a compile time error that indicates that an ElementType constant appears more than once in the target comment. For example, the following meta comments are illegal:

Extensions enum < ElementType > program element type. Constants of this enumeration type provide a simple classification of elements declared in a java program.

These constants are used with the target meta annotation type to specify when it is legal to use the annotation type.

ANNOTATION_ Type annotation type declaration constructor construction method declaration field field field declaration (including enumeration constants) local_variable declaration method declaration package declaration parameter parameter parameter declaration type class, interface (including annotation type) or enumeration declaration

Examples of restrictions on the use of annotations:

9. Add comments to the help document:

To add the annotation information to the API file while making the Javadoc file, you can use Java lang.annotation. Documented。

To declare a build annotation document in a custom annotation:

Use custom annotations:

10. Use inheritance in annotations:

By default, annotations are not inherited into subclasses. You can add Java lang.annotation. The inherited annotation declares the use of inheritance.

@Documented @ retention (value = runtime) @ target (value = annotation_type) public @ interface inherited indicates that the annotation type is automatically inherited. If there is an inherited meta annotation in the annotation type declaration, and the user queries the annotation type in a class declaration, and there is no annotation of this type in the class declaration, the annotation type will be automatically queried in the superclass of the class. This process is repeated until the annotation of this type is found or the top level (object) of the class hierarchy is reached. If no superclass has comments of that type, the query indicates that the current class has no such comments.

Note that if you use an annotation type to annotate anything other than a class, this meta annotation type is invalid. Also note that this meta annotation only facilitates inheritance of annotations from superclasses; Invalid comment on implemented interface.

The above article on Java custom annotations and obtaining annotations by reflection at runtime is all the content shared by Xiaobian. I hope it can give you a reference and support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>