005-java's annotation

Source: Internet
Author: User

I. Overview

annotation,jdk1.5 started offering

II. Basic Definitions

 public @Interface  HelloWorld {}

1, use @interface definition, name capital

2, the use of @target decoration can be placed on those class attributes, do not write is able to modify any Java

3, meta-annotations Retentionpolicy, indicating the life cycle of annotations:

1, SOURCE: In the original file is valid, is discarded by the compiler.
2, Class: In the class file is valid, may be ignored by the virtual machine.
3. Runtime: Valid at run time.

4, members, defined in the annotations "cannot be class type, object type, etc., but class can"

 Public String name ();

Add default value

 Public default "HelloWorld";

If there is only one member and is value, you can omit it and write the value directly when you use it.

5. Use

@HelloWorld (name = "Nihao1")publicclass  Testbean {    = "Nihao2")     Private  String name;    @Override    = "Nihao3")    public  String toString () {
System.out.println ("zhixing"); return this. Name + "]"; }}

Iii. main role

1, for the above do not do any processing actually no use

2, parse annotation, and then deal with the problem

 Public classParser { Public voidParse (Object obj, String methodName) {method[] Ms=Obj.getclass (). GetMethods ();  for(Method m:ms) {if(M.getname (). Equals (MethodName)) {if(M.isannotationpresent (HelloWorld.class) ) {HelloWorld HW= M.getannotation (HelloWorld.class); Try{System.out.println ("Before ..."); M.invoke (obj,NULL); System.out.println ("After ..."); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }                }            }        }    }}

3, the main method of annotation treatment

4, can replace the XML configuration

005-java's annotation

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.