Java annotation, Java Annotation

Source: Internet
Author: User

Annotation

Annotaions (also known as metadata) provide a formalized way to add information to yourcode so that you can easily use that data at some later point.
Defining annotationshere is the definition of the annotation above. You can see that annotation definitions look a lot like interface definitions.

In fact, they compile to class files like any otherJava Interface: Apart from the @ symbol, the definition of @ test is much like that of an empty interface.

An Annotation definition also requires the meta-Annotations@ Target and @ retention.

@ Target defines where you can apply this Annotation(A method or a field, for example ).

@ Retention defines whether the annotations are availableinThe (source), In the classfiles (class), or at run time (runtime).

E.g .:

// Usecase. javapackage annotationtest; import Java. lang. annotation. elementtype; import Java. lang. annotation. retention; import Java. lang. annotation. retentionpolicy; import Java. lang. annotation. target; @ target (elementtype. method) @ retention (retentionpolicy. runtime) Public @ interface usecase {public int ID (); Public String description () Default "no description";} // passwordutils. javapackage annotationtest; public class passwordutils {@ usecase (ID = 1, description = "Validate password") Public Boolean validatepassword (string password) {return true;} @ usecase (ID = 2, description = "encrypt password") Public Boolean encryptpassword (string password) {return true;} @ usecase (ID = 3, description = "checkfor password") Public Boolean checkforpassword (string password) {return true ;}// test. javapackage annotationtest; import Java. lang. reflect. method; public class test {/*** @ Param ARGs */public static void main (string [] ARGs) {method [] Methods = passwordutils. class. getdeclaredmethods (); For (method M: Methods) {usecase UC = m. getannotation (usecase. class); system. out. println ("ID =" + UC. ID () + ", description =" + UC. description () ;}}// from: Thinking in Java.

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.