[New Features of Java 5] Annotation

Source: Internet
Author: User

[New Features of Java 5] Annotation
Annotation Overview

Annotation is the metadata support provided by JDK 5.0 and later. It can be read during compilation, loading, and running and processed accordingly. Annotation provides a method to set metadata for program elements. It can be used to modify the declaration of packages, classes, constructors, methods, member variables, parameters, and local variables, the information is stored in the "name = value" pair of Annotation.

Annotation can be used to set metadata for program elements (classes, methods, member variables, and so on), such as the author of a piece of code or telling the compiler to disable some special errors without affecting code execution.

Basic Annotation

Java provides three basic Annotation usage. When using Annotation, add the @ symbol before it and use this Annotation as a modifier, it is used to modify the program elements supported by it. These three basic Annotation are defined under the java. lang package. You can refer to the API documentation for details.

@ Override: restrict the Override of the parent class method. @ Override is used to specify the method for overwriting. It can force a subclass to overwrite the method of the parent class.
Public class Fruit {public void info () {System. out. println (this is a Fruit. Do you want to eat it ?); } Public class Apple extends Fruit {@ Override public void info () {System. out. println (this is not only a Fruit, it is an Apple .);}}

If the info () method name of the Apple class is written as inf (), the compiler reports an error. It is worth noting that @ Override can only be used to modify methods and other program elements.

@ Deprecated: indicates that it is out of date. @ Deprecated indicates that a program element is outdated. When other programs use outdated classes and methods, the compiler will give a warning.
Public class Fruit {@ Deprecated public void info () {System. out. println (this is a Fruit. Do you want to eat it ?); } Public class DeprecatedTest {public static void main (String [] args) {// an underscore is displayed when the info () method is used, indicating that the method is out of date. new Fruit (). info ();}}
@ SuppressWarnings: suppress compiler warnings. @ SuppressWarnings indicates that the Code modified by this Annotation is canceled and the specified compiler warning is displayed.
Public class SuppressWarningsTest {public static void main (String [] args) {@ SuppressWarnings (rawtypes)/** when defining the List set, no generic type is specified. ** by default, a compiler warning is reported. ** after @ SuppressWarnings is used for annotation, the warning is canceled. */List list = new ArrayList ();}}
Custom Annotation

To customize an Annotation type, use the @ interface keyword to define a new Annotation type, which is very similar to defining an interface (with only one @ symbol added ).

// Customize an Annotation type public @ interface Test {}

A custom Annotation type can be used to modify classes, methods, variables, and interfaces in a program. Generally, Annotation is used before the code.

// The Custom Annotation type is defined on the class. @ Testpublic class AnnotationTest {// The Custom Annotation type is defined on the member variable. @ Test private int I; // The Custom Annotation type is defined on the constructor. @ Test public AnnotationTest () {}// the custom Annotation type is defined on the method. @ Test // The Custom Annotation type is defined on the method parameter. public void fun (@ Test String str) {// The Custom Annotation type is defined on the variable. @ Test int z ;}}
Annotation attributes

Custom Annotation can not only be in this simple form, but also contain member variables. The custom Annotation member variable is declared in the form of an intangible parameter. Its Method Name and return value define the name and type of the member variable.

/*** Custom Annotation ** @ author Jin Yunlong */public @ interface UserInfo {String username (); String password ();}

When using a custom Annotation with an attribute, you must use its attribute to specify the value; otherwise, an error is returned.

@UserInfo(username=zhangwuji,password=123)public class UserInfoTest {}

Custom Annotation can not only set attributes, but also set default values for attributes, using the default keyword.

/*** Custom Annotation with the username and password attributes ** sets the default value for the username attribute. * @ author Jin Yunlong */public @ interface UserInfo {String username () default zhangwuji; String password ();}

If the default value is set for the custom Annotation attribute, you can not specify a value for this attribute during use (use the default value ). You can also specify a value for the Annotation attribute, so the default value does not work.

The custom Annotation has an attribute named value. If you only use the value Attribute when using this Annotation, you can directly specify the value without specifying the attribute name.

@UserInfo(jiaozhu)public class UserInfoTest {}

The attribute type of Annotation can only be basic type, String, Enum, Class, and one-dimensional array of the preceding type.

@ Target Annotation

@ Target: modifies the custom Annotation and specifies which program units can be used to modify the custom Annotation, such as methods and member variables. @ Target annotation contains a value Attribute of the ElementType type. The attribute values can only be:

ElementType. ANNOTATION_TYPE: specifies that the Annotation of this policy can only be modified. ElementType. CONSTRUCTOR: specifies that the Annotation of this policy can only modify the CONSTRUCTOR. ElementType. FIELD: specifies that the Annotation of this policy can only modify member variables. ElementType. LOCAL_VARIABLE: specifies that the Annotation of this policy can only modify local variables. ElementType. METHOD: Specifies the Annotation of the policy and can only modify the METHOD definition. ElementType. PACKAGE: specifies that the Annotation of this policy can only modify the PACKAGE definition. ElementType. PARAMETER: specifies that the Annotation of this policy can only modify parameters. ElementType. TYPE: Specifies the Annotation of the policy to modify the class, interface, or enumeration definition.

The source code of @ Target annotation and the source code of ElementType are as follows:

@Target(ElementType.ANNOTATION_TYPE)public @interface Target {    ElementType[] value();}public enum ElementType {    TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE}
@ Retention Annotation

@ Retention: modifies the custom Annotation and specifies the lifecycle of the custom Annotation. @ Retention contains a RetentionPolicy type value attribute, which can only be the following:

RetentionPolicy. CLASS: the compiler records Annotation in the class file. When a Java program is running, the JVM cannot obtain Annotation information. The default value. RetentionPolicy. RUNTIME: the compiler records Annotation in the class file. When running a Java program, the JVM can also obtain Annotation information. The program can obtain this Annotation information through reflection. RetentionPolicy. SOURCE: Annotation is only stored in the SOURCE code, and the compiler directly discards This Annotation.

The following is the source code of the @ Retention annotation and the source code of the RetentionPolicy:

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Retention {    RetentionPolicy value();}public enum RetentionPolicy {    SOURCE, CLASS, RUNTIME}
Read Annotation through reflection

After Annotation is used to modify classes, methods, and member variables, the Annotation does not take effect on its own. The Annotation information must be extracted and processed through the corresponding program. The Annotation interface provided by Java is the parent interface of all annotations. The AnnotatedElement interface is added in JDK 5.0, which provides the method for reading Annotation during runtime. Only when the custom Annotation uses @ Retention (RetentionPolicy. RUNTIME) Will the Annotation be visible during running and the JVM can read the Annotation information stored in the class file.

The method API provided by the AnnotatedElement interface is as follows:

Method Summary  
T GetAnnotation (Class annotationClass)
Annotation [] GetAnnotations ()
Annotation [] GetDeclaredAnnotations ()
Boolean IsAnnotationPresent (Class AnnotationClass)

You can obtain the Annotation information of a specific type as follows:

Public class AnnotatedElementTest {public static void main (String [] args) throws Exception {// obtain the Class Object of the corresponding Class. class
  
   
Clazz = UserInfoTest. class; // obtain the Method object of the corresponding class Method. method method = clazz. getMethod (fun); // get the Annotation on the class. userInfo anno1 = clazz. getAnnotation (UserInfo. class); // print the username attribute value of the annotation. system. out. println (anno1.username (); // gets the Annotation on the method. userInfo anno2 = method. getAnnotation (UserInfo. class); // print the username attribute value of the annotation. system. out. println (anno2.password ());}}
  
JDBC annotation configuration case

When using JDBC to connect to the MySQL database, the driverClassName, url, username, And password parameters are required. The previous practice was to write the four parameters into a configuration file and read the configuration file in the JDBCUtils tool class. Currently, four parameters can be defined as an annotation. In the JDBCUtils tool class, the content of the four parameters defined in the corresponding annotation can be obtained through reflection. The procedure is as follows:

Define an Annotation to define the four parameters required for JDBC connection to the MySQL database.
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface JDBCInfo {    String driverClassName();    String url();    String username();    String password();}
Defines the JDBCUtils tool class, configures four parameters using Annotation, and reads data using reflection.
Public class JDBCUtils {@ JDBCInfo (driverClassName = com. mysql. jdbc. driver, url = jdbc: mysql: // localhost: 3306/jdbc, username = root, password = root) public static Connection getConnection () throws Exception {// get the annotation to modify the reflection object corresponding to the target. method method = JDBCUtils. class. getDeclaredMethod (getConnection); // determines whether the current annotation if (method. isAnnotationPresent (JDBCInfo. class) {// obtain the annotation information JDBCInfo jdbcInfo = method. getAnnotation (JDBCInfo. class); // read the annotation attribute information String driverClassName = jdbcInfo. driverClassName (); String url = jdbcInfo. url (); String username = jdbcInfo. username (); String password = jdbcInfo. password (); // The Class loads the driver Class. forName (driverClassName); // return the connection object return DriverManager. getConnection (url, username, password);} return null ;}}
Compile a test class to test whether the JDBCUtils tool class is correct.
public class JDBCTest {    public static void main(String[] args) throws Exception {        Connection conn = JDBCUtils.getConnection();        String sql = select * from products;        PreparedStatement statement = conn.prepareStatement(sql);        ResultSet rs = statement.executeQuery();        while (rs.next()) {            System.out.println(rs.getString(name) + , + rs.getDouble(price));        }        rs.close();        statement.close();        conn.close();    }}
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.