Table of Contents
Author's Message
Home Java JavaBase Java annotations - Java's own configuration files

Java annotations - Java's own configuration files

Jan 06, 2022 pm 03:46 PM
java

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles