Java custom annotations and reading annotations with reflection

Source: Internet
Author: User

One, custom annotations

Meta-Annotations: 

@interface Annotations: Defining annotation interfaces

@Target annotations: Used to constrain the use of the described annotations, and compilation fails when the described annotations go beyond the scope of use. such as: Elementtype.method,elementtype.type;

@Retention annotations: Used to constrain the scope of defined annotations, with a range of three:

1, Retentionpolicy.source: The scope is the source code, used in the Java file, when the execution of Javac when the annotation is removed.

2, Retentionpolicy.class: The scope is a binary code, is in the CLASS file, when executing Java to remove the annotation.

3, Retentionpolicy.runtime: The scope of the operation, is that we can dynamically get the note.

@Documented: This comment is displayed when you specify Javadoc to generate an API document.

@Inherited: Used to specify that the described comment can be inherited by subclasses of the class it describes, and by default it cannot be inherited by its subclasses.

Custom annotation Interfaces:

1  Packagecom.java.annotation;2 3 Importjava.lang.annotation.Documented;4 ImportJava.lang.annotation.ElementType;5 Importjava.lang.annotation.Inherited;6 Importjava.lang.annotation.Retention;7 ImportJava.lang.annotation.RetentionPolicy;8 ImportJava.lang.annotation.Target;9 Ten @Target ({elementtype.method,elementtype.type}) One @Inherited A @Documented - @Retention (retentionpolicy.runtime) -  Public@InterfaceAnnotation_my { the      -String name ()default"Zhang San";//Defalt represents the default value -      -String Say ()default"Hello World"; +      -     intAge ()default21st; +      A}

Next we define an interface:

Package// Use the annotation that we just defined publicinterface Person {@        Annotation_my    publicvoid  name ();        @Annotation_my    publicvoid  say ();        @Annotation_my    publicvoid age ();

The interface is defined so that we can write the implementation class of the interface (the interface cannot be instantiated)

 Packagecom.java.annotation, @Annotation_my @suppresswarnings ("Unused") Public classStudentImplementsPerson {PrivateString name; @Override @Annotation_my (Name= "Rogue Childe")//assign a value to name default to Zhang San//When you define annotations without a default value, name must be assigned the initial values here     Public voidname () {} @Override @Annotation_my (say= "Hello world!" ")     Public voidsay () {} @Override @Annotation_my ( age=20)     Public voidAge () {}}

Then we'll write a test class to test our annotations

 Packagecom.java.annotation;Importjava.lang.annotation.Annotation;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method; Public classText {annotation[] Annotation=NULL;  Public Static voidMain (string[] args)throwsClassNotFoundException {NewText (). Getannotation (); }         Public voidGetannotation ()throwsclassnotfoundexception{Class<?> stu = Class.forName ("Com.java.annotation.Student");//Static load classBooleanIsEmpty = Stu.isannotationpresent (com.java.annotation.Annotation_my.class);//Determine if Stu is using the annotation interface we just definedif(isEmpty) {annotation=stu.getannotations ();//Gets the annotation interface in the for(Annotation a:annotation) {annotation_my my=(annotation_my) a;//cast to Annotation_my type System.out.println (Stu+ ": \ n" +my.name () + "say:" +my.say () + "my Age:" +my.age ()); }} method[] Method=stu.getmethods ();//System.out.println ("Method");  for(Method m:method) {BooleanIsmempty = M.isannotationpresent (com.java.annotation.Annotation_my.class); if(Ismempty) {annotation[] AA=m.getannotations ();  for(Annotation a:aa) {annotation_my an=(Annotation_my) A; System.out.println (M+ ": \ n" +an.name () + "say:" +an.say () + "my Age:" +an.age ()); }            }        }        //get fields by forceSystem.out.println ("Get fileds by force!")); field[] Field=Stu.getdeclaredfields ();  for(Field F:field) {f.setaccessible (true);        System.out.println (F.getname ()); } System.out.println ("Get Methods in Interfaces!"); Class<?> interfaces[] =stu.getinterfaces ();  for(class<?>c:interfaces) {method[] IMethod=C.getmethods ();  for(Method m:imethod) {System.out.println (M.getname ()); }        }    }}

Java custom annotations and reading annotations with reflection

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.