JAVA注解

 1.阅读源码时经常会有一些注解,通常是为了更加灵活的设计。代码片段一选自Netty源码:

@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Sharable {
    // no value
}

Inherited应用在类上,继承的子类会自动向上查找父类是否存在该注解。

@Sharable
public class Animal {
}
public class Dog extends  Animal {
}

测试一下:

public class MyTest {
    public static void main(String[] args) {
        boolean annotation = Dog.class.isAnnotationPresent(Sharable.class);
        System.out.print(annotation);
    }
}
Documented主要用于注释,成为公共API一部分
Retention 源码:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}

这个注解主要需要返回一个值,值如下:

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.
     注释由编译器记录在类文件中,但不需要运行时被VM保留。这是一个默认的动作。
     */
    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
}
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();
}
主要有以下几种
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
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值