Catalog
2. Examples of common Annocation s
Example 1: Generate documentation-related annotations
Example 2: Format checking at compile time (three basic notes built into JDK)
Example 3: Tracking code dependencies to achieve alternative profile functionality
4. New features of annotations in JDK8
1. Annotation Overview
- Starting with JDK 5.0, Java has added support for metadata, namely Annotation.
- Annotation is actually a special tag in your code that can be read at compile, class load, run time, and processed accordingly. By using Annotation, programmers can embed additional information in their source files without changing their logic. Code analysis tools, development tools, and deployment tools can be validated or deployed with this supplementary information
- Annotation can be used like modifiers to modify declarations of packages, classes, constructors, methods, member variables, parameters, and local variables, which are stored in Annotation's "name=value" pairs.
- In JavaSE, annotations are used for simple purposes, such as marking out obsolete functionality, ignoring warnings, and so on. Annotations play a more important role in JavaEE/Android, such as configuring any aspect of the application, replacing the cumbersome code and XML configuration left behind in older versions of JavaEE.
- Future development models are annotation-based, JPA is annotation-based, Spring 2.5 is annotation-based, Hibernate 3.x is annotation-based, and now Struts2 is part of annotation-based, annotation is a trend, to some extent: framework = annotation + reflection + design mode.
2. Examples of common Annocation s
Example 1: Generate documentation-related annotations
@author Indicates the author who developed the module, used between multiple authors,Division @version Indicate the version of this type of module @see Reference turn, that is, related topics @since From which version to add @param An explanation of a parameter in a method that cannot be written without a parameter @return A description of the return value of a method if the return value type of the method is void Can't write @exception Describe exceptions that the method may throw if it is not useful throws An explicitly thrown exception cannot be written
among
The @param @return and @exception tags are all method-only. (
Format requirements for @param: @param parameter name parameter type parameter description
Format requirements for @return: @return return return return type return value description
Format requirements for @exception: @exception exception type exception description
@param and @exception can be side-by-side multiple
package com.annotation.javadoc; /** * @author cyf * @version 1.0 * @see Math.java */ public class JavadocTest { /** * The main method of the program, the entry to the program * @param args String[] Command Line Parameters */ public static void main(String[] args) { } /** * Method for finding the area of a circle * @param radius double Radius value * @return double Area of a circle */ public static double getArea(double radius){ return Math.PI * radius * radius; } }
Example 2: Format checking at compile time (three basic notes built into JDK)
- @Override: Restricts the override of parent methods, this comment can only be used for methods
- @Deprecated: Used to indicate that the decorated element (class, method, etc.) is obsolete. Usually because the structure being modified is dangerous or there is a better choice
- @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 "Rewrite toString Method()"; } }
Example 3: Tracking code dependencies to achieve alternative profile functionality
Servlet3.0 provides annotations that make it unnecessary to deploy Servlets in a web.xml file
@WebServlet("/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <servlet-mapping>/login</servlet-mapping> </servlet-mapping>
3. Custom Notes
- Define a new Annotation type using the @interface keyword
- Custom annotations automatically inherit the java.lang.annotation.Annotation interface
- Annotation 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. We call this a configuration parameter. Types can only be eight basic data types, String types, Class types, enum types, Annotation types, arrays of all the above types.
- You can specify an initial value for an Annotation member variable when you define it, and the default keyword can be used to specify the initial value of a member variable
- If there is only one parameter member, it is recommended that the parameter name be value
- If the defined comment contains a configuration parameter, 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, you can omit "value="
- An Annotation without a member definition is called a tag; An Annotation containing member variables is called a metadata Annotation
Note: Custom notes must be accompanied by an annotated information processing process to make sense
@MyAnnotion("I love Silicon Valley") public class MyAnnotionTest{ public static void main(String[] args) { Class clazz = MyAnnotionTest.class; Annotation a = clazz.getAnnotation(MyAnnotion.class); MyAnnotion m = (MyAnnotion) a; String info = m.value(); System.out.println(info); } } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface MyAnnotion{ String value() default "atguigu"; }
Four meta-comments provided by jdk5.0:
@Retention
@Retention: Can only be used to modify an Annotation definition to specify the life cycle of the Annotation, @Rentention contains a member variable of type RetentionPolicy that must be assigned a value when using @Rentention:
- RetentionPolicy.SOURCE: Valid in source file (i.e. source file retention), the compiler discards comments for this policy directly
- RetentionPolicy.CLASS: Valid in class files (i.e. class preservation), JVM does not preserve annotations when running Java programs. This is the default
- RetentionPolicy.RUNTIME: Valid at runtime (runtime retention), and JVM retains comments when running Java programs. The program can get this comment through reflection.
public enum RetentionPolicy { SOURCE, CLASS, RUNTIME }
@Target
@Target: Used to modify the Annotation definition to specify which program elements can be modified by the modified Annotation. @ Target also contains a member variable named value. *
@Documented
@Documented: Used to specify that the Annotation class decorated with this meta-annotation will be extracted into a document by the javadoc tool. By default, javadoc does not include annotations.
- Annotations defined as Documented must have a Retention value of RUNTIME set. (
@Inherited
@Inherited: The Annotation modified by it will be inheritable. If a class uses Annotation modified by @Inherited, its subclasses will automatically have this annotation.
- For example, if a custom annotation labeled with the @Inherited annotation is labeled at the class level, the subclass can inherit the parent class level annotation
- Less used in practical applications
Understanding of metadata: String name = "atguigu";
4. New features of annotations in JDK8
Java 8 provides two improvements to annotation processing: repeatable annotations and annotations that can be used for types. In addition, reflection has been enhanced to give the name of the method parameter in Java8. This simplifies the annotations labeled on the method parameters.
1) Repeatable notes
Before JDK8:
@MyAnnotions({@MyAnnotion("I love"),@MyAnnotion("Silicon Valley")}) public class MyAnnotionTest{ public static void main(String[] args) { Class clazz = MyAnnotionTest.class; Annotation a = clazz.getAnnotation(MyAnnotions.class); MyAnnotions m = (MyAnnotions) a; MyAnnotion[] value = m.value(); for (MyAnnotion myAnnotion : value) { System.out.println(myAnnotion.value()); } } } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE,ElementType.METHOD}) @interface MyAnnotion{ String value() default "atguigu"; } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE,ElementType.METHOD}) @interface MyAnnotions{ MyAnnotion[] value(); }
After JDK8, repeatable comments can be made:
- Declare @Repeatable on MyAnnotation with a member value of MyAnnotations.class
- Meta-annotations like Target and Retention and MyAnnotations on MyAnnotation are the same
@MyAnnotion("I love") @MyAnnotion("Silicon Valley") public class MyAnnotionTest{ public static void main(String[] args) { Class clazz = MyAnnotionTest.class; Annotation a = clazz.getAnnotation(MyAnnotions.class); MyAnnotions m = (MyAnnotions) a; MyAnnotion[] value = m.value(); for (MyAnnotion myAnnotion : value) { System.out.println(myAnnotion.value()); } } } @Repeatable(MyAnnotions.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE,ElementType.METHOD}) @interface MyAnnotion{ String value() default "atguigu"; } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE,ElementType.METHOD}) @interface MyAnnotions{ MyAnnotion[] value(); }
2) Type Notes
After JDK1.8, there were two more ElementType enumeration values for the parameter type of metaannotation @Target.
- ElementType.TYPE_PARAMETER means that the annotation can be written in a declaration statement for a type variable (for example, a generic declaration).
- ElementType.TYPE_USE means that the comment can be written in any statement of type usage.
public class MyAnnotionTest{ @MyAnnotion private String name; public List<@MyAnnotion String> method1(@MyAnnotion long a) throws @MyAnnotion Exception{ String s1 = "a"; @MyAnnotion String s2 = "b"; @MyAnnotion String s3 = s1 + s2; int b = (@MyAnnotion int) a; ArrayList<String> list = new ArrayList<>(); return list; } }