Java custom annotation and java Annotation

Source: Internet
Author: User

Java custom annotation and java Annotation

Java custom Annotation

-- @ Liang WP

 

I have read the Java custom annotation content over the past two days, and I have written two pieces of code according to my own understanding. This article has three parts: annotation basis, value assignment through annotation (combined with the factory method mode), verification through annotation.

 

I. annotation Basics

1. Annotation definition: the Java file is called Annotation, which is represented by @ interface.

2. Meta annotation: some things on the @ interface are annotated as needed, including @ Retention, @ Target, @ Document, and @ Inherited.

3. annotation retention policy:

@ Retention (RetentionPolicy. SOURCE) // The annotation only exists in the SOURCE code and is not included in the class bytecode file.

@ Retention (RetentionPolicy. CLASS) // The default Retention policy. The annotation will exist in the class bytecode file, but cannot be obtained at runtime.

@ Retention (RetentionPolicy. RUNTIME) // The annotation will exist in the class bytecode file and can be obtained through reflection during RUNTIME.

4. Purpose of the annotation:

@ Target (ElementType. TYPE) // interface, class, enumeration, Annotation

@ Target (ElementType. FIELD) // constant of the FIELD and enumeration

@ Target (ElementType. METHOD) // METHOD

@ Target (ElementType. PARAMETER) // method PARAMETER

@ Target (ElementType. CONSTRUCTOR) // CONSTRUCTOR

@ Target (ElementType. LOCAL_VARIABLE) // local variable

@ Target (ElementType. ANNOTATION_TYPE) // Annotation

@ Target (ElementType. PACKAGE) // PACKAGE

5. Annotations are included in javadoc:

@ Document

6. Annotations can be inherited:

@ Inherited

7. annotation Parser: Used to parse custom annotations.

 

2. assign values through annotations (combined with the factory method mode)

1. Custom Annotation

Package lwp. annotation; import java. lang. annotation. documented; import java. lang. annotation. elementType; import java. lang. annotation. inherited; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target;/*** Init. java ** @ author beam WP July 10, 2014 */@ incluented @ Inherited @ Target ({ElementType. FIELD, ElementType. METHOD}) @ Retention (RetentionPolicy. RUNTIME) public @ interface Init {public String value () default "";}

2. Use annotations in Data Models

Package lwp. model; import lwp. annotation. init;/*** User. java ** @ author beam WP July 10, 2014 */public class User {private String name; private String age; public String getName () {return name ;} @ Init (value = "liang") public void setName (String name) {this. name = name;} public String getAge () {return age;} @ Init (value = "23") public void setAge (String age) {this. age = age ;}}

3. Use "Constructor" to act as "annotation parser"

 

Package lwp. factory; import java. lang. reflect. method; import lwp. annotation. init; import lwp. model. user;/*** UserFactory. java ** @ author beam WP July 10, 2014 */public class UserFactory {public static User create () {User user User = new User (); // obtain all methods in the User class (getDeclaredMethods is also supported) Method [] methods = User. class. getMethods (); try {for (Method method: methods) {// if this method has an annotation, assign the data in the annotation to the user object if (Method. isAnnotationPresent (Init. class) {Init init = method. getAnnotation (Init. class); method. invoke (user, init. value () ;}} catch (Exception e) {e. printStackTrace (); return null;} return user ;}}

 

4. Running code

Package lwp. app; import java. lang. reflect. invocationTargetException; import lwp. factory. userFactory; import lwp. model. user;/*** Test. java ** @ author beam WP July 10, 2014 */public class Test {public static void main (String [] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {User user = UserFactory. create (); System. out. println (user. getName (); System. out. println (user. getAge ());}}

5. Running result

liang23

 

Iii. Verification by Annotation

1. Custom Annotation

Package lwp. annotation; import java. lang. annotation. documented; import java. lang. annotation. elementType; import java. lang. annotation. inherited; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target;/*** Validate. java ** @ author beam WP July 11, 2014 */@ incluented @ Inherited @ Target ({ElementType. FIELD, ElementType. METHOD}) @ Retention (RetentionPolicy. RUNTIME) public @ interface Validate {public int min () default 1; public int max () default 10; public boolean isNotNull () default true ;}

2. Use annotations in Data Models

 

Package lwp. model; import lwp. annotation. validate;/*** User. java ** @ author beam WP July 11, 2014 */public class User {@ Validate (min = 2, max = 5) private String name; @ Validate (isNotNull = false) private String age; public String getName () {return name;} public void setName (String name) {this. name = name;} public String getAge () {return age;} public void setAge (String age) {this. age = age ;}}

 

3. annotation parser

Package lwp. check; import java. lang. reflect. field; import lwp. annotation. validate; import lwp. model. user;/*** UserCheck. java ** @ author beam WP July 11, 2014 */public class UserCheck {public static boolean check (User user) {if (user = null) {System. out. println ("!! The verification object is blank !! "); Return false;} // obtain all attributes of the User class (if getFields is used, the private attributes cannot be obtained) Field [] fields = User. class. getDeclaredFields (); for (Field field: fields) {// if the attribute has an annotation, verify if (Field. isAnnotationPresent (Validate. class) {Validate validate = field. getAnnotation (Validate. class); if (field. getName (). equals ("age") {if (user. getAge () = null) {if (validate. isNotNull () {System. out. println ("!! Age blank verification failed: cannot be blank !! "); Return false;} else {System. out. println ("age can be blank verification passed: Can be blank"); continue ;}} else {System. out. println ("age can be null verified");} if (user. getAge (). length () <validate. min () {System. out. println ("!! The minimum age length cannot be verified !! "); Return false;} else {System. out. println ("minimum age length verified");} if (user. getAge (). length ()> validate. max () {System. out. println ("!! The maximum age length cannot be verified !! "); Return false;} else {System. out. println ("the maximum length of age is verified") ;}} if (field. getName (). equals ("name") {if (user. getName () = null) {if (validate. isNotNull () {System. out. println ("!! Name can be blank verification failed: cannot be blank !! "); Return false;} else {System. out. println ("name can be empty verification passed: Can be blank"); continue ;}} else {System. out. println ("the name can be null verified");} if (user. getName (). length () <validate. min () {System. out. println ("!! The minimum Name Length verification fails !! "); Return false;} else {System. out. println ("The minimum name length is verified");} if (user. getName (). length ()> validate. max () {System. out. println ("!! The maximum Name Length cannot be verified !! "); Return false;} else {System. out. println (" the maximum name length is verified ") ;}}} return true ;}}

4. Running code

Package lwp. app; import lwp. check. userCheck; import lwp. model. user;/*** Test. java ** @ author beam WP July 11, 2014 */public class Test {public static void main (String [] args) {User user = new User (); user. setName ("liang"); user. setAge ("1"); System. out. println (UserCheck. check (user ));}}

5. Running result

Name can be empty verification by name minimum length verification by name maximum length verification by age can be empty verification by age minimum length verification by age maximum length verification by true

 

 


Can java customize annotations?

The upstairs is about comments --!
Annotation is a special method. On the other hand, it is a tag and some processing is performed when this tag is encountered.
For example
In the seam framework, if an annotation is added to a class
@ Name ("semesterResultList ")
During compilation, the annotation program will compile the class named "semesterResultList" action and store it in the memory.
Annotations are a way to solve configuration clutter. Similar to preprocessing.

How does Eclipse customize java class annotations?

Choose Window> Preference from the menu to open the parameter settings panel, and then select:
Java-> Code Style-> Code Templates> Files :/**
* @ Title: A. java * @ Package * @ Description: TODO
* @ Author soszou
*/2. When creating a class, select the "Generate comments" checkbox. You can add your custom comments to the newly created class.

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.