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