Use of annotations and custom annotations

Source: Internet
Author: User
Tags deprecated reflection
three basic annotations in the JDK
A, @Override: checking subclasses is indeed a method that overrides the parent class.
B, @Deprecated: The description is outdated.
C, @SuppressWarnings ({"Unused", "deprecation"}): Suppresses warnings in programs. The type of unused warning. {} array. All suppresses all warnings.

Simple to use:

public class Demo1 {

    //@SuppressWarnings ({"Deprecation", "unused"})
    @SuppressWarnings (' all ')
    public void Fun ()
    {
        int i = 5;
        System.out.println ("Hello");
        System.out.println (New Date (). toLocaleString ());
    }

}
Class Tests extends Demo1
{
    @Override public
    Void Fun ()
    {
        super.fun ();
    } 
    @Deprecated public
    void TT ()
    {
        System.out.println (new Date (). toLocaleString ());
    }


Declare a note @interface note name {}

Public @interface myannotation{}

Annotation its essence is an interface, this interface needs to inherit annotation interface.

Public interface Myannotation extends Java.lang.annotation.Annotation {
}

Attribute type of annotation:

    1. Basic type
    2.String
    3. Enum type
    4. Annotation type
    5.Class type
    6. Type of one-dimensional array of the above types

Specifically how to define it, we look at the code:

The public @interface MyAnno1 {

    ///annotations are defined in attribute
    int age () default;
    String[] Name () default "hehe";
    String value () default "haha";
    Love Love ();
    MyAnno2 anno ();

    public static final int num = 5;//can
    //public abstract void Fun ();//error
}

To use a custom annotation:

public class Demo2 {

    //@MyAnno1 (age=25,name={"Jack", "Lucy"},value= "Zhengzhi")
    //@MyAnno1 (value= " Zhengzhi ")
    @MyAnno1 (value=" Zhengzhi ", love=love.eat) public
    void tests ()
    {

    }

}

If you use a custom annotation without a default value, we need to set the value of the attribute in the note. Reflection of Annotations: (Soul)

Simulate JUnit's @test

A, reflective annotation class
java.lang.reflect.AnnotatedElement:
<t extends annotation> T Getannotation (class<t> annotationtype): Gets the annotation reference of the specified type. No null returned.
annotation[] getannotations (): Gets all annotations, including those inherited from the parent class.
annotation[] getdeclaredannotations (): Get a note of yourself.


boolean isannotationpresent (class< extends annotation> annotationtype): Determine if the specified annotation is not.

Class, method, Field, constructor, etc. implement the Annotatedelement interface.
if: Class.isannotationpresent (mytest.class): Judge class above there is no @mytest annotation;
method.isannotationpresent (Mytest.class): There is no @mytest annotation on the method.

The following code is implemented.
We simulate the ability to implement @test annotations
First of all, this is our note @mytest

Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Meta-Annotations:
@Retention (retentionpolicy.runtime) public @interface to annotate annotations (
MyTest) {
    long timeout () default integer.max_value;//set timeout Time
}

This is the class where we use annotations:

public class Dbcrud {

    @MyTest (timeout=1000000) public
    void Addtest ()
    {
        System.out.println () Addtest method executed ");
    }

    @MyTest public
    void Updatetest ()
    {
        System.out.println ("Updatetest method executed");
    }


When we use annotations, we need to determine whether the class uses annotations, which we implement by reflection.

private static void Method1 () throws Illegalaccessexception,
            InvocationTargetException, instantiationexception {

        class Claz = dbcrud.class;//Gets the bytecode file object

        //Gets all the methods in the class and the parent class
        method[] methods = Claz.getmethods ();

        For (methods M:methods) {
            ///Whether the method uses @mytest this annotation
//          Boolean boo = M.isannotationpresent (mytest.class);          System.out.println (M.getname () + "= =" +boo);//All is false the default annotation survives to CLASS, and the change survives to runtime
            if ( M.isannotationpresent (Mytest.class)) {
                M.invoke (claz.newinstance (), null);}}}
    

* * Here we need to be aware that we need to take into account the survival scope of the custom annotations.
The default custom annotation only survives to the compile time, class stage.

Notice that our custom annotation above applies the @retention annotation, which changes the scope of the custom annotation.

This annotation is also called meta annotation, which can only be used in annotations, which are called meta annotations.
**
The method above does not take into account the problem of timeout, let's refine it below.

Method1 ();
        Reflection Parsing Annotation attribute
        Class Claz = dbcrud.class;

        Method[] methods = Claz.getmethods ();
            for the MyTest annotation
            MyTest mt = m.getannotation (Mytest.class) for the method M:methods {//);
            if (mt!=null) {
                //Get the attribute in the annotation
                long out = Mt.timeout ();
                Long start = System.nanotime ();
                M.invoke (claz.newinstance (), null);
                Long end = System.nanotime ();
                if ((End-start) >out)
                {
                    System.out.println ("Run timeout");
                }
            }

        

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.