[chapter 09 Java annotation] let you fully understand this "Annotation" with great potential in the future

❤ Write in front
❤ Blog home page: Hard working Naruto
❤ Series column: Java basic learning 😋
❤ Welcome, friends, praise 👍 follow 🔎 Collection 🍔 Learning together!
❤ If there are mistakes, please correct them! 🌹

🔥 Series portal:
[chapter 08 Java enumeration classes] easy to understand enum
[chapter 07 common Java classes] check common Java classes
[chapter 06 multithreading] the highlight of Java language [hot list]
[chapter 05 Java exception handling] a short article teaches you to play with Java exception handling [hot list]
[appendix 2Java object-oriented programming] detailed explanation of inventory keywords this, super and final [hot list]
[chapter 04 Java object-oriented programming (Part 2)] the killer technology of object-oriented programming [hot list]
[chapter 04 Java object-oriented programming (middle)] decrypt inheritance and polymorphism [hot list]
[chapter 04 Java object-oriented programming (Part I)] the first experience of everything being an object [second in the hot list of the whole station]
For more, see > > > Java basic learning 😋

1, Annotation

Annotation
Future development models are based on annotations

🔥 Annotation overview

Annotations are actually special tags in the code,
These tags can be read during compilation, class loading, and runtime, and the corresponding processing can be performed

  1. Annotations are used like modifiers to modify declarations of packages, classes, constructors, methods, member variables, parameters, and local variables
  2. In Java se, annotations are used for simple purposes, such as marking outdated functions, ignoring warnings, etc
  3. Annotations play a more important role in Java EE / Android, such as configuring any aspect of the application, replacing the cumbersome code and XML configuration left over from the old version of Java EE

Frame = annotation + reflection + design pattern

2, Common notes

🔥 Generate document related annotations

● @ author indicates the author who developed this kind of module. It can be used and divided among multiple authors
● @ version indicates the version of such modules
● @see reference turns, i.e. related topics
● @ since which version was added
● @ param describes a parameter in the method. If there is no parameter, it cannot be written
  format requirements: @ param parameter name parameter type parameter description
● @ return describes the return value of the method. If the return value type of the method is void, it cannot be written
  format requirements: @ return return return value type return value description
● @ exception describes the exceptions that may be thrown by the method. If the method does not explicitly throw an exception with throws, it cannot be written
  format requirements: @ exception exception type exception description
code:

package com.annotation.javadoc;
/**
* @author shkstart
* @version 1.0
* @see Math.java
*/
public class JavadocTest {
		/**
		* The main method of the program, the entry of the program
		* @param args String[] Command line parameters
		*/
		public static void main(String[] args) {
		}
		/**
		* Method for calculating circular area
		* @param radius double Radius value
		* @return double Area of circle
		*/
		public static double getArea(double radius){
		return Math.PI * radius * radius;
	}
}

🔥 Format check at compile time

Three basic annotations built into JDK

  1. @Override: restrict overriding parent class methods. This annotation can only be used for methods
  2. @Deprecated: indicates that the modified element (class, method, etc.) is outdated, usually because the modified structure is dangerous or has a better choice
  3. @SuppressWarnings: suppress compiler warnings
package com.annotation.javadoc;
public class AnnotationTest{
		public static void main(String[] args) {
			@SuppressWarnings("unused")
			int a = 10;
		}
		@Deprecated
		public void print(){
			System.out.println("Outdated methods");
		}
		@Override
		public String toString() {
		return "Rewritten toString method()";
	}
}

🔥 Track code dependencies and realize the function of replacing configuration files

●Servlet3.0 provides annotations so that they are no longer needed on the web Deploy servlets in XML files
Example:

@WebServlet("/login")

● management of "transaction" in spring framework

@Transactional(propagation=Propagation.REQUIRES_NEW,
				isolation=Isolation.READ_COMMITTED,readOnly=false,timeout=3)
		public void buyBook(String username, String isbn) {
		//1. Unit price of query
		int price = bookShopDao.findBookPriceByIsbn(isbn);
		//2. Update inventory
		bookShopDao.updateBookStock(isbn);
		//3. Update user's balance
		bookShopDao.updateUserAccount(username, price);
}

3, Custom annotation

  1. The @ interface keyword is required for customization
  2. Automatically inherited Java lang.annotation. Annotation interface
  3. Member variables are declared as parameterless methods in the Annotation definition
    Its method name and return value define the name and type of the member, which are called configuration parameters
    The type can only be eight basic data types, String, Class, enum, Annotation, and arrays of all the above types
  4. When defining the member variable of Annotation, you can specify its initial value, which can use the default keyword
  5. If the definition annotation contains configuration parameters, the parameter value must be specified when using, unless it has a default value
    The format is "parameter name = parameter value". If there is only one parameter member and the name is value
@MyAnnotation(value="Hard working Naruto")
public class MyAnnotationTest {
		public static void main(String[] args) {
		Class clazz = MyAnnotationTest.class;
		Annotation a = clazz.getAnnotation(MyAnnotation.class);
		MyAnnotation m = (MyAnnotation) a;
		String info = m.value();
		System.out.println(info);
	}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation{
		String value() default "xiaomingren";
}

4, Meta annotation

The meta annotation of JDK is used to modify other annotation definitions
The four meta annotations are:
●Retention
●Target
●Documented
●Inherited

👌Retention

1. Used to specify the lifecycle of the Annotation
2. @ retention contains a member variable of RetentionPolicy type
3. When using @ rention, you must specify a value for the value member variable:
●RetentionPolicy.SOURCE: it is valid in the source file. The compiler directly discards the comments of this strategy
●RetentionPolicy.CLASS: it is valid in the class file. When running a Java program, the JVM will not keep the annotation as the default value
●RetentionPolicy.RUNTIME: valid at runtime. When running Java programs, the JVM will keep comments. The program can get the comment through reflection

@Retention(RetentionPolicy.SOURCE)
@interface MyAnnotation{ }

👌Target

  1. Used to specify which program elements can be modified by the modified Annotation
  2. @Target also contains a member variable named value

👌Documented

  1. It is used to specify that the Annotation class modified by the meta Annotation will be extracted into a document by the javadoc tool
  2. By default, javadoc does not include annotations
  3. Annotations defined as Documented must have the Retention value set to RUNTIME

👌Inherited

  1. The decorated Annotation will be inherited
  2. Its subclasses also automatically have this annotation

🎁 Conclusion: annotations can make people understand the code written by others, especially the framework related code. It is even more powerful to use custom annotations to solve problems
👌 The author is a Java beginner. If there are errors in the article, please comment and correct them in private letters and learn together~~
😊 If the article is useful to the friends, praise it 👍 follow 🔎 Collection 🍔 Is my biggest motivation!
🚩 Step by step, nothing to a thousand miles, book next time, welcome to see you again 🌹

Keywords: Java Back-end

Added by fredi_bieging on Sun, 23 Jan 2022 11:22:48 +0200