Annotation详解

演示所需bean

这里写图片描述

AnEnum

public enum AnEnum { A,B,C; }

BaseAnnotation

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by admin on 2017/1/18.
 */
@Target(value = {ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface BaseAnnotation {
}

CsAnnotation

import java.lang.annotation.*;

/**
 * Created by admin on 2017/1/18.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
@Documented
@Repeatable(CsAnnotationContainer.class)
public @interface CsAnnotation {
/*  1.所有基本数据类型(int,float,boolean,byte,double,char,long,short)
    2.String类型
3.Class类型
4.enum类型
5.Annotation类型
6.以上所有类型的数组*/
    int value();
    String name() default "name";
    Class cls() default CsAnnotation.class;
    BaseAnnotation baseAnnotation() default @BaseAnnotation;
    AnEnum anEnum() default AnEnum.A;
    int[] array() default {};
}

CsAnnotationContainer

import java.lang.annotation.*;

/**
 * Created by admin on 2017/1/18.
 */
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CsAnnotationContainer {
    CsAnnotation[] value();
}

AnBean

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.ArrayUtils;

/**
 * Created by admin on 2017/1/18.
 */

public class AnBean {

    @CsAnnotation(value = 1, name = "normal", array = {1}, baseAnnotation = @BaseAnnotation, anEnum = AnEnum.A,cls = AnBean.class)
    private final static int normal=1;

    @CsAnnotation(value = 2, name = "repeat", array = {1,2}, baseAnnotation = @BaseAnnotation, anEnum = AnEnum.B,cls = AnBean.class)
    @CsAnnotation(value = 3, name = "repeat", array = {1,2}, baseAnnotation = @BaseAnnotation, anEnum = AnEnum.C,cls = AnBean.class)
    private final static int repeat=2;

    public static void main(String[] args) throws Exception{
        {
            System.out.println(String.format("------单个注解------"));
            CsAnnotation annotation = AnBean.class.getDeclaredField("normal").getAnnotation(CsAnnotation.class);

            int value = annotation.value();
            System.out.println(String.format("value-->%s", value));
            String name = annotation.name();
            System.out.println(String.format("name-->%s", name));
            AnEnum anEnum = annotation.anEnum();
            System.out.println(String.format("anEnum-->%s", anEnum.name()));

            BaseAnnotation baseAnnotation = annotation.baseAnnotation();
            System.out.println(String.format("baseAnnotation-->%s", baseAnnotation.annotationType().getName()));
            Class cls = annotation.cls();
            System.out.println(String.format("cls-->%s", cls.getName()));

            int[] array = annotation.array();
            System.out.println(String.format("array-->%s", JSON.toJSONString(array)));
        }

        {
            System.out.println(String.format("------可重复注解------"));
            CsAnnotation[] annotationsByType = AnBean.class.getDeclaredField("repeat").getAnnotationsByType(CsAnnotation.class);
            if (ArrayUtils.isNotEmpty(annotationsByType)) {
                for (int i = 0; i < annotationsByType.length; i++) {
                    CsAnnotation annotation = annotationsByType[i];
                    System.out.println(String.format("-------------%s-------------", i));

                    int value = annotation.value();
                    System.out.println(String.format("value-->%s", value));
                    String name = annotation.name();
                    System.out.println(String.format("name-->%s", name));
                    AnEnum anEnum = annotation.anEnum();
                    System.out.println(String.format("anEnum-->%s", anEnum.name()));

                    BaseAnnotation baseAnnotation = annotation.baseAnnotation();
                    System.out.println(String.format("baseAnnotation-->%s", baseAnnotation.annotationType().getName()));
                    Class cls = annotation.cls();
                    System.out.println(String.format("cls-->%s", cls.getName()));

                    int[] array = annotation.array();
                    System.out.println(String.format("array-->%s", JSON.toJSONString(array)));
                }
            }
        }
    }
}

AnBean.class(AnBean生成的class)

import com.alibaba.fastjson.JSON;
import com.cs.annotation.AnEnum;
import com.cs.annotation.BaseAnnotation;
import com.cs.annotation.CsAnnotation;
import com.cs.annotation.CsAnnotationContainer;
import org.apache.commons.lang3.ArrayUtils;

public class AnBean {
    @CsAnnotation(
        value = 1,
        name = "normal",
        array = {1},
        baseAnnotation = @BaseAnnotation,
        anEnum = AnEnum.A,
        cls = AnBean.class
    )
    private static final int normal = 1;
    @CsAnnotationContainer({@CsAnnotation(
    value = 2,
    name = "repeat",
    array = {1, 2},
    baseAnnotation = @BaseAnnotation,
    anEnum = AnEnum.B,
    cls = AnBean.class
), @CsAnnotation(
    value = 3,
    name = "repeat",
    array = {1, 2},
    baseAnnotation = @BaseAnnotation,
    anEnum = AnEnum.C,
    cls = AnBean.class
)})
    private static final int repeat = 2;

    public AnBean() {
    }

    public static void main(String[] args) throws Exception {
        System.out.println(String.format("------单个注解------", new Object[0]));
        CsAnnotation annotationsByType = (CsAnnotation)AnBean.class.getDeclaredField("normal").getAnnotation(CsAnnotation.class);
        int i = annotationsByType.value();
        System.out.println(String.format("value-->%s", new Object[]{Integer.valueOf(i)}));
        String annotation = annotationsByType.name();
        System.out.println(String.format("name-->%s", new Object[]{annotation}));
        AnEnum value = annotationsByType.anEnum();
        System.out.println(String.format("anEnum-->%s", new Object[]{value.name()}));
        BaseAnnotation name = annotationsByType.baseAnnotation();
        System.out.println(String.format("baseAnnotation-->%s", new Object[]{name.annotationType().getName()}));
        Class anEnum = annotationsByType.cls();
        System.out.println(String.format("cls-->%s", new Object[]{anEnum.getName()}));
        int[] baseAnnotation = annotationsByType.array();
        System.out.println(String.format("array-->%s", new Object[]{JSON.toJSONString(baseAnnotation)}));
        System.out.println(String.format("------可重复注解------", new Object[0]));
        CsAnnotation[] var10 = (CsAnnotation[])AnBean.class.getDeclaredField("repeat").getAnnotationsByType(CsAnnotation.class);
        if(ArrayUtils.isNotEmpty(var10)) {
            for(i = 0; i < var10.length; ++i) {
                CsAnnotation var11 = var10[i];
                System.out.println(String.format("-------------%s-------------", new Object[]{Integer.valueOf(i)}));
                int var12 = var11.value();
                System.out.println(String.format("value-->%s", new Object[]{Integer.valueOf(var12)}));
                String var13 = var11.name();
                System.out.println(String.format("name-->%s", new Object[]{var13}));
                AnEnum var14 = var11.anEnum();
                System.out.println(String.format("anEnum-->%s", new Object[]{var14.name()}));
                BaseAnnotation var15 = var11.baseAnnotation();
                System.out.println(String.format("baseAnnotation-->%s", new Object[]{var15.annotationType().getName()}));
                Class cls = var11.cls();
                System.out.println(String.format("cls-->%s", new Object[]{cls.getName()}));
                int[] array = var11.array();
                System.out.println(String.format("array-->%s", new Object[]{JSON.toJSONString(array)}));
            }
        }

    }
}

输出结果

------单个注解------
value-->1
name-->normal
anEnum-->A
baseAnnotation-->com.cs.annotation.BaseAnnotation
cls-->com.cs.annotation.AnBean
array-->[1]
------可重复注解------
-------------0-------------
value-->2
name-->repeat
anEnum-->B
baseAnnotation-->com.cs.annotation.BaseAnnotation
cls-->com.cs.annotation.AnBean
array-->[1,2]
-------------1-------------
value-->3
name-->repeat
anEnum-->C
baseAnnotation-->com.cs.annotation.BaseAnnotation
cls-->com.cs.annotation.AnBean
array-->[1,2]

总结

@Retention

package java.lang.annotation;

/**
 * Annotation retention policy.  The constants of this enumerated type
 * describe the various policies for retaining annotations.  They are used
 * in conjunction with the {@link Retention} meta-annotation type to specify
 * how long annotations are to be retained.
 *
 * @author  Joshua Bloch
 * @since 1.5
 */
public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

分别对应:Java源文件(.java文件)—->.class文件—->内存中的字节码

@Target

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}

@Repeatable(1.8新增注解)

主要用于解决1.8之前无法重复注解的问题
从示例代码看来字段repeate中是将定义了多个简单注解@CsAnnotation在编译的时候转换成@Repeatable(CsAnnotationContainer.class) CsAnnotationContainer注解
编译结果是在class中已经不存在@CsAnnotation
也无法使用field.getAnnotation(CsAnnotation .class)来获取到
只能使用field.getAnnotationsByType(CsAnnotation .class)或者field.getAnnotation(CsAnnotationContainer.class)来获取字段repeate上的注解信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值