Java gets annotations on classes, methods, properties __annotation

Source: Internet
Author: User
to get annotations on a class

The annotations on the Java fetch class have the following 3 methods: Class.getannotations () gets all the annotations, including their declared and inherited Class.getannotation (class< A > Annotationclass Gets the specified annotation, which can either be declared by itself or an inherited class.getdeclaredannotations () to obtain the annotations of its own declaration

Next, let's demonstrate the use of 3 methods.
First, we define two annotations parentannotation, subannotation

@Retention (retentionpolicy.runtime)
@Target (Value={elementtype.type})
@Documented
@Inherited  / /You can inherit the public
@interface parentannotation {

}

@Target (Value={elementtype.type})
@Retention ( Retentionpolicy.runtime)
@Documented public
@interface subannotation {

}

Next, we define two classes, Parent, Sub, annotated parentannotation annotation and subannotation annotation respectively.

@ParentAnnotation public
class Parent {

}

@SubAnnotation public
class Sub extends parent{

}

When all is ready, the test begins.

public class Annotationtest {public static void main (string[] args) {annotation[] Allannos = Sub.class.getA
        Nnotations ();
        annotation[] Deannos = Sub.class.getDeclaredAnnotations ();
        Annotation subannotation = Sub.class.getAnnotation (Subannotation.class);
        Annotation parentannotation = Sub.class.getAnnotation (Parentannotation.class);
        Printannotation ("All", Allannos);
        Printannotation ("declare", Deannos);
        Printannotation ("Sub", subannotation);
    Printannotation ("parent", parentannotation); } private static void Printannotation (String msg,annotation ... annotations) {System.out.println ("============
        = = "+msg+" ====================== ");
        if (annotations = = null) {System.out.println ("Annotation is null");
        for (Annotation annotation:annotations) {System.out.println (Annotation);
    } System.out.println (); Results in execution: ==============all===================== = @com. Ghs.test.annotation.ParentAnnotation () @com. Ghs.test.annotation.SubAnnotation () ==============declare==== ================== @com. Ghs.test.annotation.SubAnnotation () ==============sub====================== @ Com.ghs.test.annotation.SubAnnotation () ==============parent====================== @ Com.ghs.test.annotation.ParentAnnotation ()

Try to remove the @inherited from the parentannotation, and the result is as follows:

==============all======================
@com. Ghs.test.annotation.SubAnnotation ()

==============declare ======================
@com. Ghs.test.annotation.SubAnnotation ()

==============sub===================== =
@com. Ghs.test.annotation.SubAnnotation ()

==============parent======================
null

Try to remove the subannotation from the Sub class, and the results are as follows:

==============all======================

==============declare======================

==============sub= =====================
null

==============parent======================
NULL

After a few small tests, we can basically draw the following conclusions: annotations only @inherited to quilt class inheritance when a class does not annotate any annotations, getannotations () and Getdeclaredannotations () return an empty array When an annotation query is not available, the getannotation (class< A > Annotationtype) method returns null two, and gets the annotation on the method

Modify the above parentannotation and subannotation so that it can be annotated on the method
@Target (Value={elementtype.type, Elementtype.method})

In sub, parent, add a test () method separately, as follows:

@ParentAnnotation public
class Parent {

    @ParentAnnotation public
    Void Test () {

    }
}

@ Subannotation public
class Sub extends parent{

    @SubAnnotation public
    Void Test () {

    }
}

Everything is ready to be tested.

private static void Testmethodannotation () {
    method[] methods = Sub.class.getMethods ();
    For (method Method:methods) {
        if (Method.getname (). Equals ("Test")) {
            annotation[] Allmannos = Method.getannotations ();
            annotation[] Demannos = Method.getdeclaredannotations ();
            Annotation Submanno = method.getannotation (subannotation.class);
            Annotation Parentmanno = method.getannotation (parentannotation.class);
            Printannotation ("Allmannos", Allmannos);
            Printannotation ("Demannos", Demannos);
            Printannotation ("Submanno", Submanno);
            Printannotation ("Parentmanno", Parentmanno);
        }
    }

The results of the implementation are as follows:

==============allmannos======================
@com. Ghs.test.annotation.SubAnnotation ()

============== demannos======================
@com. Ghs.test.annotation.SubAnnotation ()

==============submanno======== ==============
@com. Ghs.test.annotation.SubAnnotation ()

==============parentmanno===================== =
NULL

Try deleting the test method in sub and testing again with the following result:

==============allmannos======================
@com. Ghs.test.annotation.ParentAnnotation ()

============ ==demannos======================
@com. Ghs.test.annotation.ParentAnnotation ()

==============submanno== ====================
null

==============parentmanno======================
@ Com.ghs.test.annotation.ParentAnnotation ()

After two rounds of testing, the following conclusions can be drawn: The subclass overrides the method, the annotation cannot be inherited for the method, the result of Getannotations () and getdeclaredannotations () always seems to be the same.
Attached: In view of this conclusion, if there are different ideas, but also hope to comment Three, get the annotation on the attribute

Modify the above parentannotation and subannotation so that it can be annotated on the property
@Target (Value={elementtype.type, Elementtype.method,elementtypefield})

In sub, parent, add a Name property separately, as follows:

@ParentAnnotation public
class Parent {

    @ParentAnnotation public
    String name;

    @ParentAnnotation public
    Void Test () {

    }
}

@SubAnnotation public
class Sub extends parent{

    @ Subannotation public
    String name;

    @SubAnnotation public
    Void Test () {

    }
}

Start the test below:

private static void Testfieldannotation () {
    field[] fields = Sub.class.getFields ();
    for (Field field:fields) {
        annotation[] allfannos= field.getannotations ();
        annotation[] Defannos = Field.getdeclaredannotations ();
        Annotation Subfanno = field.getannotation (subannotation.class);
        Annotation Parentfanno = field.getannotation (parentannotation.class);
        Printannotation ("Allfannos", Allfannos);
        Printannotation ("Defannos", Defannos);
        Printannotation ("Subfanno", Subfanno);
        Printannotation ("Parentfanno", Parentfanno);
        System.out.println ("**************************************************\n");
    }

The results of the implementation are as follows:

==============allfannos======================
@com. Ghs.test.annotation.SubAnnotation ()

============== defannos======================
@com. Ghs.test.annotation.SubAnnotation ()

==============subfanno======== ==============
@com. Ghs.test.annotation.SubAnnotation ()

==============parentfanno===================== =
null

**************************************************

==============allfannos================= =====
@com. Ghs.test.annotation.ParentAnnotation ()

==============defannos======================
@ Com.ghs.test.annotation.ParentAnnotation ()

==============subfanno======================
null

= = ============parentfanno======================
@com. Ghs.test.annotation.ParentAnnotation ()

********** ****************************************

After testing, we can draw the following conclusions: the properties of the parent class and the attribute complementary interference of subclasses for attributes, the getannotations () and Getdeclaredannotations () methods return the same results.
Attached: In view of this conclusion, if there are different ideas, but also look at the generous enlighten

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.