JAVA-depth comment -Annotation (the learning process)

JAVA study notes -Annotation

Purpose of this article: project development process encountered custom annotations, you want to figure out the principle, but not enough to support their own knowledge base to explore this issue, we first recorded question, then added the basics, and then solve its problems. Record this learning process.

Encountered in the project notes:

//使用注解的地方
@ServiceScan({"com.sinosoft.lis.pubfun"})
public class CodeQuerySQL {}

//注解类 ServiceScan
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceScan {
    String[] value() default {};
}

//这个com.sinosoft.lis.pubfun包下的类
@CodeQuery
public interface CodeQuery_Framework {}

//注解类CodeQuery
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CodeQuery {
}

Problem Description: development, we need to create a new codequeryframework_nb own class that is used on the next com.sinosoft.lis.pubfun package on the line, and then customize the method, it will automatically be scanned and then automatically loads interface methods defined by class, to achieve our inquiry pull-down function. Use the correct notes, including the right place can be used, but why does not conflict with previous codequeryframework? Specifically how to achieve, members of our group did not thoroughly understand. I decided to annotate the depth of knowledge to dig a dig.

Our question:

  1. This function is how to achieve.
  2. Why not previously created and class conflict.
  3. In fact, how to achieve.

Learning objectives:

  1. Be able to explain: why this class is how to achieve through annotations
  2. Understand what annotations are, how to use notes, annotations implementation principle

Notes Basics added:

learning process:

  1. First, go first to a data probably has some knowledge of notes. https://www.runoob.com/w3cnote/java-annotation.html
  2. Discover some of the bloggers blog to see what they are mentioned in the big points, are basically the same, so you can navigate to first understand what they need is to learn and understand
  3. For questions about the process, a leak filled. For their own doubts

Knowledge of other people mentioned: java5, meta-annotation, custom comment to the realization of annotation properties, notes the role of the use of annotations in reflection

Nature annotations

//「java.lang.annotation.Annotation」接口中有这么一句话,用来描述『注解』。
The common interface extended by all annotation types
所有的注解类型都继承自这个普通的接口(Annotation)

Let's just opening the annotation within a JDK, look at how the definition of

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

This is the definition @Override notes, in fact, it essentially is:

 public interface Override extends Annotation{
     
 }

Yes, nature is an inherited annotation interface Annotation interface. In this regard, you can go to decompile any of the annotation class, you will get results.

Why use annotations?

Here found the resolve of the two bloggers, I feel very easy to understand place. First to an understanding on the whole.

In usually I do not know if we have used sticky notes, write several sentences on a piece of paper, attached to the place we need. There is also a situation that most people call our program ape (less money, then die fast), this is a label attached to us. Like these two cases it is basically a comment. You can think of these two cases to comment on the code. For example, we define a method, this method to achieve an addition operation, then we can define a @ADD label. It indicates that this method is to achieve addition. We see this a programmer @ADD, can easily understand this method is doing. In simple terms. Notes that the code of certain fresh individuals posted up for a label. Simplified terms, annotated as a label. Because, if you have not yet formally studied notes before you can put him as a convenient label like this can help you understand most of annotations.

Previously, "XML" is favored by the major framework that loosely coupled way to complete a framework for virtually all configurations, but with more and more large projects, the contents of "XML" has become increasingly complex, maintenance costs Becomes high. So some people put forward a markup of high coupling type configuration, "notes." The method can be annotated, the class can be annotated, the field attributes can also be annotated, where almost anyway you need to configure can be annotated. About "notes" and "XML" in two different configuration modes, debated for many years, each have their own advantages and disadvantages, annotations can provide greater convenience, ease of maintenance modification, but high coupling, and with respect to XML comment is reversed. We should abandon the pursuit of low coupling efficiency, the pursuit of efficiency is bound to encounter coupling. This article is intended to no longer discriminate who is superior to both, but in the most simple language to introduce notes related to the basic content.

Yuan notes

Yuan notes role:

"Meta-annotation" is used to modify the annotated notes, usually in the definition annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

This is our definition of @Override annotations, you can see them @ Target, @ Retention two notes is what we call "meta-annotation", "meta-annotation" is generally used to specify an annotation information life cycle and the role of goals .

So what are meta-annotation
//目前jdk官方提供的元注解有4个
@Target:定义注解的作用目标
@Retention:定义注解的生命周期
@Documented:定义注解是否应当被包含在 JavaDoc 文档中
@Inherited:定义是否允许子类继承该注解
Detailed yuan notes
  1. @Target - who the target is used to indicate the modified annotated ultimately the role that is specified in your comment in the end is used to modify the method? Modified class? Or used to modify field properties. Target is defined as follows:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}

We can pass values ​​by the way this value:

 @Target(value = {ElementType.FIELD})

This annotated modified @Target comment will only act on the member field, it can not be used to modify the method or class. Which, ElementType is an enumeration type, there are some of the following values:

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,  //允许被修饰的注解作用在类、接口和枚举上

    /** Field declaration (includes enum constants) */
    FIELD, //允许作用在属性字段上

    /** Method declaration */
    METHOD,  //允许作用在方法上

    /** Formal parameter declaration */
    PARAMETER, //允许作用在方法参数上

    /** Constructor declaration */
    CONSTRUCTOR, //允许作用在构造器上

    /** Local variable declaration */
    LOCAL_VARIABLE,  //允许作用在本地局部变量上

    /** Annotation type declaration */
    ANNOTATION_TYPE,  //允许作用在注解上

    /** Package declaration */
    PACKAGE,   //允许作用在包上

    /**
     * Type parameter declaration
     * 表示该注解能写在类型变量的声明语句中(如:泛型声明)。
     * @since 1.8 
     */
    TYPE_PARAMETER,  

    /**
     * Use of a type
     * 表示该注解能写在使用类型的任何语句中。
     * @since 1.8
     */
    TYPE_USE
}

注意:上述中文翻译为自己翻译的,如果有错误,请自行查阅官方文档
最后从jdk1.8添加的两个枚举类型的作用,是通过搜索网络资料查询得来
类型注解: JDK1.8之后,关于元注解@Target的参数类型ElementType枚举值多了两个:
TYPE_PARAMETER和TYPE_USE。

在Java8之前,注解只能是在声明的地方所使用,Java8开始,注解可以应用在任何地方。
ElementType.TYPE_PARAMETER 表示该注解能写在类型变量的声明语句中(如:泛型声明)。
ElementType.TYPE_USE 表示该注解能写在使用类型的任何语句中。
  1. @Retention - identify how this annotation saved, only in code, or incorporated into the class file, or can be accessed via reflection at runtime. It is substantially defined as follows:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}

Similarly, it also has a value attribute:

@Retention(value = RetentionPolicy.RUNTIME

RetentionPolicy here is still an enumerated type, it has the following desirable enumeration values:

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,  //当前注解编译期可见,不会写入 class 文件

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,  //类加载阶段丢弃,会写入 class 文件

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME  //永久保存,可以反射获取
}

@Retention annotation specifies that the annotated modified life cycle, only one is visible at compile time, it will be discarded after compiling a file will be compiled into class in the compiler, either class or method, and even field they are all property sheet, and JAVA virtual machine also defines several annotations attribute table for storing annotation information, but this can not be brought visibility area method, will be discarded when the class is loaded, the last one is visibility permanent.

How to verify the life cycle?

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
public @interface TestAnnotation {
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation2 {
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface TestAnnotation3 {
}
@TestAnnotation
@TestAnnotation2
@TestAnnotation3
public class TestJava {
    public static void main(String[] args) throws ClassNotFoundException {
        Class<?> testJava = Class.forName("com.sinosoft.lis.pubfun.TestJava");
        Annotation[] annotations = testJava.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation.annotationType());
        }

    }

You know what I mean.

  1. @Inherited - mark this comment which is inherited annotation class (default to comment and did not inherit any subclass) in.
  2. @Documented - mark these notes is contained in the user documentation.

The remaining two types of annotation of our daily use of small, relatively simple, there were no detailed description, and only need to know their respective roles.
@Documented notes modified comment, when we execute JavaDoc documentation package doc will be saved into the document, and vice versa will be discarded when packaging.
@ Inherited annotation comment is a modified inheritable, also notes that we modify a class, and that class subclass will automatically inherit the parent class the comment.

JAVA provides a built-in three notes

#### 除了上述四种元注解外,JDK 还为我们预定义了另外三种注解,它们是:
1. @Override
2. @Deprecated
3. @SuppressWarnings
JAVA provides a built-in three notes - Detailed

1. @Override comment you must be very familiar with the labeled rewrite method, which is defined as follows:

/**
 * Indicates that a method declaration is intended to override a
 * method declaration in a supertype. If a method is annotated with
 * this annotation type compilers are required to generate an error
 * message unless at least one of the following conditions hold:
 *
 * <ul><li>
 * The method does override or implement a method declared in a
 * supertype.
 * </li><li>
 * The method has a signature that is override-equivalent to that of
 * any public method declared in {@linkplain Object}.
 * </li></ul>
 *
 * @author  Peter von der Ah&eacute;
 * @author  Joshua Bloch
 * @jls 9.6.1.4 @Override
 * @since 1.5
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

It does not have any property, so do not store any other information. It can only act on the above method, it is discarded after the end of the compilation. So you see, it is a typical "tag type notes," only shows the compiler, the compiler in the process of java files compiled into byte code, upon detection of the method is a modification of the comment , horses will go on whether the parent class has a function the same method signature, if not, could not compile.

2. @Deprecated: mainly used to mark the Element outdated, substantially defined as follows

/**
 * A program element annotated &#64;Deprecated is one that programmers
 * are discouraged from using, typically because it is dangerous,
 * or because a better alternative exists.  Compilers warn when a
 * deprecated program element is used or overridden in non-deprecated code.
 *
 * @author  Neal Gafter
 * @since 1.5
 * @jls 9.6.3.6 @Deprecated
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}

Is still a "marker annotation type" permanent, you can modify all types, is to mark the current class or method, or field, etc. is no longer recommended for use, may be the next version of the JDK will be deleted. Of course, the compiler does not enforce what you do, just tell your JDK is no longer recommended using the current method or class, I suggest you use a replacement.

3. @SuppressWarnings : java primarily used to suppress the warning, which is substantially defined as follows:

/**
 * Indicates that the named compiler warnings should be suppressed in the
 * annotated element (and in all program elements contained in the annotated
 * element).  Note that the set of warnings suppressed in a given element is
 * a superset of the warnings suppressed in all containing elements.  For
 * example, if you annotate a class to suppress one warning and annotate a
 * method to suppress another, both warnings will be suppressed in the method.
 *
 * <p>As a matter of style, programmers should always use this annotation
 * on the most deeply nested element where it is effective.  If you want to
 * suppress a warning in a particular method, you should annotate that
 * method rather than its class.
 *
 * @author Josh Bloch
 * @since 1.5
 * @jls 4.8 Raw Types
 * @jls 4.12.2 Variables of Reference Type
 * @jls 5.1.9 Unchecked Conversion
 * @jls 5.5.2 Checked Casts and Unchecked Casts
 * @jls 9.6.3.5 @SuppressWarnings
 */
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    /**
     * The set of warnings that are to be suppressed by the compiler in the
     * annotated element.  Duplicate names are permitted.  The second and
     * successive occurrences of a name are ignored.  The presence of
     * unrecognized warning names is <i>not</i> an error: Compilers must
     * ignore any warning names they do not recognize.  They are, however,
     * free to emit a warning if an annotation contains an unrecognized
     * warning name.
     *
     * <p> The string {@code "unchecked"} is used to suppress
     * unchecked warnings. Compiler vendors should document the
     * additional warning names they support in conjunction with this
     * annotation type. They are encouraged to cooperate to ensure
     * that the same names work across multiple compilers.
     * @return the set of warnings to be suppressed
     */
    String[] value();
}

It has a value attribute that you need to take the initiative to pass a value, this value represents a What does it mean, this value represents the type of warning is the need to be suppressed. E.g:

public static void main(String[] args) {
    Date date = new Date(2019, 12, 27);
}

So a piece of code, the compiler will report a warning when the program starts.

Warning: (8, 21) java: java.util.Date the Date (int, int, int) Obsolete

And if we do not want the program to start, the compiler checks your code obsolete methods, you can use @SuppressWarnings comment and give it a value attribute parameter value passed to suppress checking compiler.

@SuppressWarning(value = "deprecated")
public static void main(String[] args) {
    Date date = new Date(2019, 12, 27);
}

So you will find that the compiler will not check for outdated method calls the next main method will suppress the compiler checks for such warnings.

Of course, JAVA, there are many types of alerts, they will correspond to a character string, by setting the value attribute value to suppress this type of warning to the type of examination.

Custom annotation:

Custom annotation syntax is relatively simple, you can customize a comment by syntax similar to the following.

public @interface InnotationName{
    
}

Of course, custom annotation can be used when a meta-annotation selectivity is also modified, so you can be more specific specify your annotations life cycle, scope and other information.

&& annotation properties using annotations

Annotation property also known as member variables. Notes Only members of variables, there is no way. Annotated member variable defined annotation to "invisible parameter method" form to declare that the method name defines the name of the member variable, which defines the type of the return value of the member variable.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    int id();
    String msg();
}

The above code defines TestAnnotation this annotation has two properties id and msg. When in use, we ought to be assigned to them.

Before the assignment approach is to value = "" form, with a plurality of attributes in the annotation brackets, spaced apart.

Note that, in the definition of the properties of its annotation type must be applied eight primitive data type classes, interfaces, annotations and an array thereof.

Annotation properties can have default values, defaults, you need to specify a default key value. such as:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    public int id() default -1;
    public String msg() default "Hi";
}

TestAnnotation id attribute default value -1, msg attribute default value Hi. It can be so applied.

@TestAnnotation()
public class Test {}

Because of the default values, so no assignment again in the back of @TestAnnotation brackets, this step can be omitted.

Finally, one case to be noted that a property does not have any comment. such as

public @interface Perform {}

So when the application of this comment, the parentheses can be omitted.


So far: I just know how annotations are defined specifically with them is how to achieve it?

  1. For example @override is how to check? ? After opening the source code to see if it is defined it quite simple
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
  1. As another example, I added a class above @Documented comment, it will automatically generate a document according to what I wrote at the time of generation of the document doc? He is how to achieve? By scanning annotation classes to do it?
  2. As another example, previously used @bean comments, we use the time frame in spring, after the definition of java in the class will be loaded when the scan is loaded into the container it? Specifically how to achieve it?
  3. I felt I needed to write this very clear understanding of the problem. With its own estimate may reflect other people have mentioned about

Well. With these two questions, we continue to learn down.


Notes and reflection

Above us on the details of annotations, it can also briefly mentioned, "the essence of a comment is inherited Annotation interface connectors" Now we have to look at the virtual machine level, what is the nature of notes in the end yes.

Examples of the use of annotations

Too much use of local annotation, such as:
JUnit testing framework This is a typical use is as follows:

public class ExampleUnitTest {
     @Test
     public void addition_isCorrect() throws Exception {
         assertEquals(4, 2 + 2);
     }
 }

There are for example ssm framework, springboot, springcloud and so used a lot of notes.

to sum up

Considered to have a basic understanding of annotations. Talk about self-summary of it.

  1. If the notes are difficult to understand, you put it similar to the label, the label in order to explain things, annotated to explain the code.
  2. The basic syntax of annotations, create like interface, but more than a @ symbol.
  3. Meta-annotation annotations.
  4. Property annotations.
  5. The main comment to the compiler and tool type of software used.
  6. Extract annotation need the help of Java technology reflection, reflecting slower, so also need to be careful when using annotations time to care about the cost (to be studied reflection,! Important).

My previous question:

  1. I infer, my previous question, is not found in the notes above.
  2. Function question I had is through notes, reflecting done. Annotation just played a complete annotation of the function.
  3. Next you need to study it is: reflection.

By reflection scans all been modified @CodeQuery class or interface and is injected into the subject in the form of their bean container to unified management, according to the modified @CodeQuery class or interface, it can be determined modified @CodeQuery What are a nice class, class through all the files, then you can use the reflection of the method class to get the names of all @SQL modified method, you can call the corresponding interface at runtime by name method to execute sql statement the


references:

  • https://www.cnblogs.com/yangming1996/p/9295168.html
  • https://www.cnblogs.com/love-menglong/p/11165469.html
  • https://www.runoob.com/w3cnote/java-annotation.html
  • https://blog.csdn.net/tainxiawuti/article/details/99644352
  • https://www.cnblogs.com/skywang12345/ "big brother"

Extended Job

  1. Class source code review and understand the inside of the built-in methods, such as the ability to view the annotation approach reflected the class which provides:
    Class<TestJava> testJavaClass = TestJava.class;
    testJavaClass.getAnnotations();
  1. Recognizing the importance of the underlying knowledge, I felt the power of the underlying Java.
  2. Reflection of theoretical knowledge, practical application, analysis application scenarios.

Guess you like

Origin www.cnblogs.com/bigbaby/p/12109732.html