[Java5 new Features] annotation annotations

Source: Internet
Author: User
Tags deprecated

Annotation overview

Annotation is a support for metadata after JDK 5.0 that can be read at compile, load, and run time and handled accordingly. The so-called annotation provides a way to set metadata for program elements that can be used to decorate the declarations of packages, classes, constructors, methods, member variables, parameters, and local variables, which are stored in annotation's "name=value" pairs.

Annotation can be used to set metadata for program elements (classes, methods, member variables, etc.), such as the author of a piece of code, or to tell the compiler to prohibit special errors without affecting the execution of the code.

Basic annotation

The use of 3 basic annotation is provided in Java, where the @ symbol is added before the annotation and used as a modifier to decorate the program elements it supports. These 3 basic annotation are defined under the Java.lang package and can be understood by looking at the API documentation.

    • @Override: Bounds override the parent class method. @Override is used to specify how the method is to be loaded, and it can force a subclass to overwrite the parent class's method.
publicclass Fruit {    publicvoidinfo(){        System.out.println("这是一个水果,想吃吗?");    }}publicclass Apple extends Fruit {    @Override    publicvoidinfo() {        System.out.println("这不仅是一个水果,它是苹果.");    }}

If the Apple class's info () method name is written in the INF (), the compiler will error. It is important to note that @Override can only modify methods and not modify other program elements.

    • @Deprecated: The indicator is obsolete. @Deprecated is used to indicate that a program element is obsolete, and the compiler will give a warning when other programs use obsolete classes and methods.
publicclass Fruit {    @Deprecated    publicvoidinfo(){        System.out.println("这是一个水果,想吃吗?");    }}publicclass DeprecatedTest {    publicstaticvoidmain(String[] args) {        // 使用info()方法时将会出现划线,表示该方法已过时.        new Fruit().info();    }}
    • @SuppressWarnings: Suppresses compiler warnings. @SuppressWarnings indicates that the specified compiler warning is deselected by the code that is decorated by the annotation.
publicclass SuppressWarningsTest {    publicstaticvoidmain(String[] args) {        @SuppressWarnings("rawtypes")        /*         * List集合在定义时,没有指定泛型类型.         *  * 默认情况下,出现编译器警告.         *  * 使用@SuppressWarnings注释后,取消警告信息.         */        new ArrayList();    }}
Custom annotation

Customizing a annotation type using the @interface keyword, defining a new annotation type is much like defining an interface (just an @ sign).

// 自定义一个Annotation类型public @interface Test {}

Customizing a annotation type can often be used to decorate classes, methods, variables, interfaces, and so on in programs. In general, the use of annotation is preceded by the code.

//Custom annotation type is defined on the class.@Test Public  class annotationtest {    //Custom annotation type is defined on the member variable.    @Test    Private intI//Custom annotation type is defined on the constructor.    @Test     Public annotationtest(){}//Custom annotation type is defined on the method.    @Test    //Custom annotation type is defined on the method parameter.     Public void  Fun(@Test String str) {//Custom annotation type is defined on the variable.        @Test        intZ }}
Annotation Property

Custom annotation can be not only this simple form, but also include member variables. The member variable of a custom annotation is declared in the form of an invisible parameter, and its method name and return value define the name and type of the member variable.

/** * 自定义带有username和password属性的Annotation *  * @author 金云龙 */public @interface UserInfo {    String username();    String password();}

When using custom annotation with attributes, you must specify a value with its properties, or you will get an error.

@UserInfo(username="zhangwuji",password="123")publicclass UserInfoTest {}

Custom annotation Not only can you set properties, but you can also set a default value for the property, using the Defaults keyword.

/** * 自定义带有username和password属性的Annotation *  * 为username属性设置默认值. * @author 金云龙 */public @interface UserInfo {    default"zhangwuji";    String password();}

If you set a default value for a custom annotation property, you can use it without specifying a value for the property (using the default value). You can also specify a value for its properties when you use the annotation, and the default value will not work.

The custom annotation has a property named value, and you can specify the value directly without writing the property name if you use the annotation only if you use the Value property.

@UserInfo("jiaozhu")publicclass UserInfoTest {}

The annotation property type can only be a primitive type, String, Enum, class, and one-dimensional array type of the above type.

@Target annotations

@Target modifies the custom annotation, specifying which program units the custom annotation can use to decorate, such as methods, member variables, and so on. @Target annotations contain a Value property of type ElementType, which can only be as follows:

    • Elementtype.annotation_type: Specifies that the ANNOTATION of the policy can only be decorated with ANNOTATION.
    • Elementtype.constructor: Specifies that the annotation of the policy can only decorate the constructor.
    • Elementtype.field: Specifies that the annotation of the policy can only modify member variables.
    • Elementtype.local_variable: Specifies that the annotation of the policy can only modify local variables.
    • Elementtype.method: Specifies that the annotation of the policy can only modify the method definition.
    • Elementtype.package: Specifies that the annotation of the policy can only decorate the package definition.
    • Elementtype.parameter: Specifies that the annotation of the policy can only modify parameters.
    • Elementtype.type: Specifies that the annotation of the policy can decorate a class, interface, or enumeration definition.

The following is the source code of @target annotations and ElementType:

@Target(ElementType.ANNOTATION_TYPE)public @interface Target {    value();}publicenum ElementType {    TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE}
@Retention annotations

@Retention Modify Custom annotation To specify the life cycle of the custom annotation. The @Retention contains a Value property of type Retentionpolicy, which can only be a few of the following:

    • Retentionpolicy.class: The compiler will record the annotation in the CLASS file. When running a Java program, the JVM cannot obtain annotation information. This is the default value.
    • Retentionpolicy.runtime: The compiler will record the annotation in the class file. When running a Java program, the JVM can also obtain annotation information that the program can use to obtain the annotation information.
    • The RetentionPolicy.SOURCE:Annotation is only kept in the source code, and the compiler discards the annotation directly.

The following is the source code of @retention annotations and Retentionpolicy:

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

After you use annotation to decorate classes, methods, member variables, and so on, these annotation do not take effect on their own, and the annotation information must be extracted and processed by the appropriate program. The annotation interface provided by Java is the parent interface for all annotations, adding a new Annotatedelement interface to JDK 5.0, which provides a way to read the runtime annotation. Only if the custom annotation uses @retention (retentionpolicy.runtime), the annotation is visible at run time, and the JVM can read the annotation information stored in the class file.

The following is the method API provided by the Annotatedelement interface:

Method Summary
<t extends Annotation> T Getannotation (Class annotationclass)
Annotation[] Getannotations ()
Annotation[] Getdeclaredannotations ()
Boolean Isannotationpresent (class<? extends annotation> Annotationclass)

The actual way to get the annotation information used by a class is as follows:

 Public classannotatedelementtest { Public Static void Main(string[] args) throws Exception {//Gets the class object for the corresponding classes.class<userinfotest> clazz = Userinfotest.class;//Gets the method object for the corresponding class methods.method = Clazz.getmethod ("Fun");//Gets annotations on the class.UserInfo anno1 = clazz.getannotation (Userinfo.class);//Print the annotation's Username property value.System. out. println (Anno1.username ());//Get annotations on the method.UserInfo Anno2 = method.getannotation (Userinfo.class);//Print the annotation's Username property value.System. out. println (Anno2.password ()); }}
Annotation configuration jdbc Case

When using JDBC to connect to a MySQL database, you need four parameters for Driverclassname, URL, username, and password. The previous practice was to write these four parameters to a configuration file and read the configuration file in the Jdbcutils tool class. It is now possible to define four parameters as an annotation to get the four parameter content defined by the corresponding annotation in the Jdbcutils tool class through reflection. The following are the specific practices:

    • Define a annotation to define the four parameter content required for JDBC to connect to the MySQL database.
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface JDBCInfo {    driverClassName();    url();    username();    password();}
    • Define the Jdbcutils tool class, configure four parameter contents using annotation, and read with reflection.
 Public  class jdbcutils {    @JDBCInfo(Driverclassname ="Com.mysql.jdbc.Driver", url ="Jdbc:mysql://localhost:3306/jdbc", username ="Root", password ="Root") Public StaticConnectiongetconnection()throwsException {//Gets the reflection object corresponding to the callout adornment target.method = JDBCUtils.class.getDeclaredMethod ("Getconnection");//Determine if current annotations exist        if(Method.isannotationpresent (Jdbcinfo.class)) {//Get annotation informationJdbcinfo jdbcinfo = method.getannotation (Jdbcinfo.class);//Read annotation property informationString driverclassname = Jdbcinfo.driverclassname ();            String URL = jdbcinfo.url ();            String username = jdbcinfo.username (); String password = Jdbcinfo.password ();//class load driverClass.forName (Driverclassname);//Return Connection object            returnDrivermanager.getconnection (URL, username, password); }return NULL; }}
    • Write 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 ());        } rs.close ();        Statement.close ();    Conn.close (); }}

Reprint NOTE: Please indicate the author and the original link, thank you!

[Java5 new Features] annotation annotations

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.