注解Annotation

1、什么是注解
  • 注解是从JDK5.0 开始引入的技术
  • 可以看成是Java类,方法的一个扩展模板
  • 可以附加在package , class , method , field 等上面 , 相当于给他们添加了额外的辅助信息
2、自定义注解
  • 使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation 接口
import java.lang.annotation.*;

//定义一个注解
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Inherited
@Documented
@interface MyAnonocation {
    //定义参数尾部用()修饰 ,default 默认值
    String name () default "";

}
3、了解JDK提供的内置注解
  • @Override :修饰方法,表示重写父类中的方法
  • @Deprecated : 注解在方法/类上,鼓励程序员不要用调用他,可能是有bug或者有更好的方案
  • @SuppressWarnings :用来抑制编译时的警告信息
    @SuppressWarnings(“all”)
    @SuppressWarnings(“unchecked”)
    @SuppressWarnings(value={“unchecked”,“deprecation”})
4、元注解
  • @Target : 用于描述注解的使用范围
    查看下源码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}

进一步查看他的参数成员ElementType,是一个枚举

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
}
  • @Retention :用于描述注解的生命周期
    查看下源码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}

查看下他的成员变量 RetentionPolicy

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
}

(SOURCE < CLASS < RUNTIME)

  • @Document : 说明该注解将被包含在javadoc中
  • @Inherited : 说明子类可以继承父类中的该注解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值