Home > Java > JavaBase > body text

Java annotations - Java's own configuration files

向前冲!
Release: 2022-01-07 13:41:51
Original
2185 people have browsed it

Author's Message

Hello, everyone, this is my first article. I hope to summarize the knowledge I have learned and share it with you. I will share it with you in the next period of time. Publish a series of Java, Python and other entry-level related articles, and share them systematically so that you can go further by laying a solid foundation. I hope you all will give me some advice! Without further ado, let’s get down to the practical stuff! (If there is any infringement involved, please contact me through this platform to delete)

Preface

XML as a configuration file is popular among most programmers However, some people prefer to use annotations. In fact, I personally feel that the choice is not the point. The point is to understand the essence of the birth of each technology; XML as a configuration file and code is a "loosely coupled" code description, but when XML configuration When there are too many files, it is difficult to manage. At the same time, the IDE cannot verify the correctness of the XML configuration file, which increases the difficulty of testing. Annotations are "tightly coupled" code descriptions. Its purpose is to make the application easier to expand while also "Zero" configuration.

1. What is annotation

Annotation is annotation, which is the metadata in the code (metadata: data describing the data). By using annotation, Program developers can embed some supplementary information in the source files without changing the original logic. Please take a look at the following code snippet:

Java annotations - Javas own configuration files

For beginners, in fact, they often see similar code and wonder what the hell is @Override? In fact, it is an annotation. Adding @Override to the toString() method means that the toString() method under the annotation must reconstruct the parent class method.

After seeing this, I think some people will think that I will introduce various annotations to you next? ! I don't!

2. Grammar standards of annotation types

Annotations are a special type in Java. Next, let’s take a look at how to design an annotation type.

1. Grammar standard:

public   @interface   注解类型名称
{
    [   数据类型    变量名 ()    [   default  初始值   ];   ]
}
Copy after login

Note:

1) The content in "[ ]" is optional. If the annotation is empty inside, it means the current annotation Annotate the logo.

2) Annotations should intelligently include variables and cannot include methods.

3) Annotations are special marks in the code and cannot be used alone. They need to be used together with classes or interfaces.

4) Annotation types can be used to set metadata for program elements (program elements: classes, methods, member variables, etc.).

2. Case: Design the annotation type Testable, and the method identified by this annotation is a testable method. The annotation is empty internally, indicating that the annotation is an identification annotation.

public  @interface  Testable
{
}
Copy after login
public class Test

{

      @Testable

       public void info()

      {

              System.out.println(“我是info方法”);

      }

      public void info1()

      {

              System.out.println(“我是info1方法”);

      }

}
Copy after login

The @Testable annotation is added to this class to indicate that the info method is an executable method. It only describes that the method is an executable method and does not have any dynamic interaction capabilities. If you want To achieve the function of this annotation, a supporting Java application must be written. For specific code, please refer to the following code.

You can think about it, if we want to parse the internal structure of a class, what technology can we use to achieve it?

The answer is: reflection mechanism (for friends who are unclear about the reflection mechanism in the following paragraph, please follow the code below to debug. The specific knowledge about the reflection mechanism will be released later).

Common tool classes with reflection function in the java.lang.reflect package: Method (method class), Field (field class), Constructor (constructor method class), etc.

The above tool classes expand the ability to read runtime annotations, that is, implement the java.lang.annotation.AnnotatedElement interface; this interface is the parent interface of all program elements, and this interface provides functions for obtaining annotations information related methods.

  • getAnnotation(Class annotationClass): Returns the annotation of the specified type on the program element. If the annotation of this type does not exist, returns null

  • Annotation [] getAnnotations(): Returns all annotations that exist on the program element.

  • Annotation is the parent interface of all annotations. By default, any interface type implements this interface.

  • boolean isAnnotationPresent(Class annotationClass): Determines whether the program element contains annotations of the specified type. If it exists, it returns true, otherwise it returns false.

Code reference:

Parse the Test class and execute the method marked with @Testable.

import java.lang.reflect.Method;
public class UseTest
{
        public static void main(String[] args)throws Exception
        {
                  Class c=Class.forName(“Test”);
                  Object o=c.newInstance();
                  Method[] me=c.getDeclaredMethods();
                  for(Method temp:me)
                  {
                           if(temp.isAnnotationPresent(Testable.class))
                                   temp.invoke(o,new Object[0]);
                  }
         }
}
Copy after login

Okay, now you can run the program to see the effect!

. . . . . . .

Isn’t it particularly speechless (ˉ▽ˉ;)..., by executing the code, you will find that the program has no results, which is different from what we thought? !

If you want to know what happened next time, please read the breakdown next time!

3. Summary:

Next, let us summarize the knowledge points that friends need to master.

1. The difference between XML and annotations

2. What are annotations

3. Grammar standards for annotation design

4. Reflection mechanism

5. Methods and functions of java.lang.annotation.AnnotationElement

4. Conclusion

Let me tell you the reason why I ended in a hurry. This is the first time When I write an article, I don’t know what the content format will be like. Please read the next article for the remaining relevant knowledge. Thank you for your support.

The above is the detailed content of Java annotations - Java's own configuration files. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template