[Reprint] java annotations core knowledge summary

 

java annotation core knowledge summary

Disclaimer: This article is a blogger original article, follow the  CC 4.0 BY-SA  copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_45674354/article/details/102864317

1 Introduction

A few years ago we ran 2 projects are still structs, once asked a colleague know that Spring Boot, colleagues say it is not used to develop the right notes. While the answer is not exactly right, but from an objective Spring Boot for people new to it is the most eye-catching is annotated. Well, today we look at the core features of the Java language - annotations.

2. What is the comment

public @interface Anno { }

The above is a simple statement notes. It can comment on classes, interfaces, methods, and variables. By the methods, interfaces, classes, fields, or add comments assigned additional metadata source for binding.

3. Use annotations
by annotation we can tell the compiler warnings and errors operation or modify the source code at compile time checking behavior at runtime. 5 provides substantially built jdk annotation processing code checks.

  • @Override to mark the method to rewrite or replacement behavior inherited methods. If you override the parent class method without the notes will trigger some warnings.
  • @SuppressWarnings mean that we should ignore certain parts of the code of the warning. As ignore potentially unsafe type conversion warnings unchecked.
  • @Deprecated used to represent the class, out of date and is not recommended. If you are forced to use the compiler will warn at compile time.
  • @Safevarargs suppression "heap pollution" warning. "Heap pollution" refers to the type of problems caused when an object is a generic without assigned to the variable with generics. If you do not want to see this warning can use this annotation to suppress.
  • @FunctionalInterface java 8 new notes, can only act on the interface up to identify the interface is a function interface. Java interface function represented in the interface can have an abstract method. If the interface is a modification of this comment, if you add a second abstract methods will not compile.

Some metadata annotation can be passed to the logic you write. A common example of annotation @RequestMapping Spring Mvc, we can pass through a path path parameter value, Spring Mvc to be made whether the route of the path through path matching request. Currently a large number of frameworks rely annotations, such as Spring, hibernate, dubbo and so on.

4. yuan notes

Meta-annotation can be applied to other annotated notes. To enhance or configuration of the target annotation mechanism. jdk currently offers five yuan notes. If you need to develop custom annotation, be sure to be familiar with them:

  • @Retention can only be used to modify the notes, annotations can be modified to specify for how long. Sets out three strategies:
  • Under such a policy is modified RetentionPolicy.SOURCE annotations can only exist in the source code, compiled discarded after, can not be acquired by reflecting the modified annotation.
  • Under this strategy RetentionPolicy.CLASS modified notes will be compiled into bytecode files. But the JVM can not be modified to obtain comment. This is a default value when you declare annotations without adding any retention policy, specify the policy by default.
  • Under RetentionPolicy.RUNTIME this strategy can only be modified notes compiled into bytecode files. And JVM can also acquire the modified annotated notes. And program code can also get some meta information is modified by the annotation annotation reflection.
  • @Target used to modify the target type is modified annotations. If a comment can be modified to clear the target type, then specify the type of modification only. Specified by the enumeration ElementType.
  • TYPE can only be modified classes, interfaces, enumerations.
  • FIELD can only modify member variables, constants in the enumeration contains.
  • METHOD only modification methods.
  • PARAMETER only modifies parameters.
  • CONSTRUCTOR can only be modified constructor.
  • LOCAL_VARIABLE only modifies a local variable.
  • ANNOTATION_TYPE only modifies comment.
  • PACKAGE only modifies package definition. That is, in package-info.java
  • TYPE_PARAMETER java 8 indicates that the new notes can be written on the declaration type parameters. Type parameter declarations such as:,
  • TYPE_USE java 8 new annotation can be used again anywhere in the type of use.
  • @Documented modified by the annotation notes can be extracted javadoc documentation tool.
  • @Inherited modified by the annotation notes have inherited. Between some key points to note here is first class embodies this inheritance instead of interfaces, and notes must be visible to the JVM. That is @Retention to RetentionPolicy.RUNTIME to work.
  • @Repeatable java 8 new. Prior to this in the same element can appear only once with a comment. @Repeatable can make a comment multiple times over an element.

5. custom annotation

Custom annotation with custom interface is similar, but there are some differences, you need to actually develop custom annotation meta-annotation notes. Member variable comment in reference to non-abstract method to declare member variables and not all types are supported, currently only supports the following types:

  • All basic types (int, float, boolean, byte, double, char, long, short)
  • String
  • Class (如:Class<?> 或 Class)
  • enum java enum
  • Annotation
  • Here we customize a comment:
  • /**
     * Can declare a mark in classes, interfaces, enumerations, annotations on the method.
     * JVM Runtime visible and can generate documents
     *
     * @author Dax
     * @since 17 :27 2019/9/4
     */
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE, ElementType.METHOD})
    public @interface Anno {
     /**
     * If a method called value statements and notes only need to declare the value attribute,
     * Value can be omitted, @Anno ( "anno") is equivalent to @Anno (value = "anno")
     *
     * @return the string
     */
     String value();
     /**
     * A String attribute defaults have.
     * Name if not explicitly declared, the default is "." 
     * Declare a default value is declared by default + defaults
     *
     * @return the string
     */
     String name() default "";
     /**
     * A Class type attribute, with no default. Other types are no longer supported for example
     *
     * @return the class
     */
     Class<?> clazz();
    }

     

How to get metadata annotation of
the subclass of all the notes are java.lang.annotation.Annotation. Only RetentionPolicy can get to RUNTIME comments by reflection. Providing reflective AnnotatedElement interface to process the packet to capture the annotation element. The interface is a parent interface Class, Method, Constructor program elements like object. That is as long as the acquisition program element object can process its existing notes. The main methods are:

  • boolean isAnnotationPresent (Class <? extends Annotation> annotationClass) annotationClass determine whether the type of annotation.
  • T getAnnotation (Class annotationClass) If the parameter is present on the current element type (annotationClass) annotations specified, returns the corresponding annotations, otherwise, it returns null.
  • Annotation [] getAnnotations () Returns all annotations on this element. If the element is not annotated, the return value is an array of length zero. The caller of this method is free to modify the returned array; it does not affect the other array is returned to the caller.
  • T [] getAnnotationsByType (Class annotationClass) Returns the annotation associated with the element. If no annotation associated with this element, the value of 0 returns the length of the array. This method differs from that getAnnotation (Class), the method detects whether its argument is a reusable type of annotation (JLS 9.6), if so, attempt "looking through" to find a container of the type annotation or more annotations . The caller of this method is free to modify the returned array; it does not affect the other array is returned to the caller. Reference @Repeatable.
  • T getDeclaredAnnotation (Class annotationClass) If the parameter specified types of notes are directly present on the current element, the corresponding return annotations, otherwise, it returns null. This method ignores inherited annotations. (If you do not comment directly on this element, null is returned.)
  • T [] getDeclaredAnnotationsByType (Class annotationClass) is available but ignored repeated notes inherited annotations.
  • Annotation [] getDeclaredAnnotations () above with the difference that the annotation can not acquire repeated annotations.

Basically this method after learning the interface may know how to get the metadata annotation. Let's write an example or above Anno notes as an example:

/**
 * Annotated's marker
 **/
@Anno("hello")
public class Foo {}
/**
 * Through the acquisition of Class Foo class,
 * Then you can get the value of value of the method according to the above has been described
 * @author dax
 * @since 2019/9/4 22:17
 */
public class Main {
 public static void main(String[] args) {
 Anno annotation = Foo.class.getAnnotation(Anno.class);
 String value = annotation.value();
 System.out.println("value = " + value);
 }

 

Summarize
today we systematically notes were summarized, I believe you have to have a systematic understanding of annotations.

Source: Nuggets link: https://juejin.im/post/5db79e6c6fb9a0206f47bfd2

Private letter reply "Information" get the interview book "Java Core knowledge finishing .pdf" ", covering the JVM, locks, high concurrency, reflection, Spring Principle

Guess you like

Origin www.cnblogs.com/jinanxiaolaohu/p/12000521.html