Java Annotation Technology (Annotation)

Source: Internet
Author: User

What is Annotation?Add a new feature named Annotation to the released JDK1.5 (tiger. Annotation provides a mechanism to associate program elements such as classes, methods, attributes, parameters, local variables, packages, and metadata. In this way, the compiler can store metadata in the Class file. In this way, virtual machines and other objects can decide how to use these program elements or change their behavior based on the metadata.What is Annotation?Annotation is actually a special mark in the Code. It is often used to replace configuration files (such as web. xml ).Location of Annotation?Annotations can be added to classes, interfaces, methods, method parameters, fields, and local variables.Common meta-Annotation? Meta Annotation refers to the Annotation for modifying the Annotation. Common meta-Annotation includes @ Retention, @ Target, @ shortented,@ Inherited:
@ Resolve ention: Used to specify the domain that can be retained by the Annotation. @ resolve ention contains an entionpolicy type attribute, specifying the domain: entionpolicy. CLASS: the compiler records the annotation in the Class file. When a java program is run, the jvm does not keep the annotation. This is the default value. Entionpolicy. RUNTIME: the compiler records the annotation in the file. When a java program is running, the jvm retains the annotation. Entionpolicy. SOURCE: the compiler directly discards the annotation of this policy. Note: entionpolicy. RUNTIME is our most common value.@ Target: Specifies the members of The annotation. Attribute values are some values in ElementType of Enumeration type.@ Brief ented: Specifies that the Annotation class modified by this Annotation will be extracted as a document by the javadoc tool.@ Inherited: The Annotation modified by it will be Inherited. If a class uses the Annotation modified by @ Inherited, its subclass will automatically have this Annotation.

Annotation Declaration

Package cn.edu. chd. annotation;/*** @ author Rowand jj *** this is an annotation example *** 1. annotation receiving types include: * String type, basic data type, Class type, enumeration type, annotation type, and one-dimensional array of the above types * Other types are not allowed, for example, List list (); // This is incorrect ** 2. if the name of an attribute is value, you can call this annotation without specifying the name: * public @ interface annotation * {* String value, @ demo ("zhangsan") is equivalent to @ demo (value = "zhansgan") **/public @ interface MyAnnotation {String name (); // added a property String password () default "123" for this annotation; // configure the default value int age () default 13; Gender gender () default Gender. FEMAIL; // Enumeration type, with the default value Class clazz (); // a Class type MyAnnotation2 my2 (); // annotation nested annotation int [] arr () default {1, 23, 4}; // array}

Note:
@MyAnnotation(name="zhansgan",age=33,clazz=MyAnnotationDemo.class,my2=@MyAnnotation2(like="chifan"))    public void aa()    {            }

Application Scenario 1: Use annotations as configuration files to provide runtime parameters for methods
Package cn.edu. chd. annotation; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy;/*** @ author Rowand jj ** Save the annotation of the database connection parameters ** @ Retention (RetentionPolicy. RUNTIME) This specifies that the scope of the current annotation is RUNTIME */@ Retention (RetentionPolicy. RUNTIME) public @ interface DBInfo {String url () default "jdbc: mysql: // localhost: 3306/db_test"; String username () default "root"; String password () default "root ";}

Package cn.edu. chd. annotation; import java. lang. reflect. method; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. SQLException; public class JDBCUtils {@ DBInfo (password = "sjjhong") public static Connection getConnection (String url, String username, String password) throws SQLException {return DriverManager. getConnection (url, username, password);}/*** obtain the annotation information on the method through reflection */public static void main (String [] args) throws Exception {Method method = JDBCUtils. class. getMethod ("getConnection", String. class, String. class, String. class); DBInfo info = method. getAnnotation (DBInfo. class); String url = info. url (); String password = info. password (); String username = info. username (); // call method System. out. println (method. invoke (null, url, username, password ));}}

Console output: com. mysql. jdbc. JDBC4Connection @ 3bcd288e, parameters are obtained successfully. Application Scenario 2: Object injection through annotation Technology
package cn.edu.chd.annotation2;public class Person{    private String name;    private int age;    public String getName()    {        return name;    }    public void setName(String name)    {        this.name = name;    }    public int getAge()    {        return age;    }    public void setAge(int age)    {        this.age = age;    }    }



package cn.edu.chd.annotation2;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME)public @interface InjectPerson{    String name();    int age();}

package cn.edu.chd.annotation2;public class PersonDao{    private Person person;    public Person getPerson()    {        return person;    }    @InjectPerson(name="hehe",age=12)    public void setPerson(Person person)    {        this.person = person;    }}

Package cn.edu. chd. annotation2; import java. beans. propertyDescriptor; import java. lang. reflect. field; import java. lang. reflect. method; public class Demo {public static void main (String [] args) throws Exception {// 1. get the property PropertyDescriptor pd = new PropertyDescriptor ("person", PersonDao. class); // 2. class clazz = pd is required for the property to be injected. getPropertyType (); // 3. object p = clazz. newInstance (); // 4. method setPerson = pd. getWriteMethod (); // 5. the annotation InjectPerson inject = setPerson declared on the reflection method. getAnnotation (InjectPerson. class); // 6. get the declared information on the annotation, and fill in the person object Method [] methods = inject. getClass (). getMethods (); for (Method m: methods) {String methodName = m. getName (); try {Field f = Person. class. getDeclaredField (methodName); Object value = m. invoke (inject, null); f. setAccessible (true); f. set (p, value) ;}catch (Exception e) {continue ;}// 7. the person filled with data is rounded up to the personDao object by using the setPerson method. PersonDao dao = new PersonDao (); setPerson. invoke (dao, p); System. out. println (dao. getPerson (). getName ());}}

Console output: hehe

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.