注解学习1

2017-09-12  本文已影响74人  走在冷风中吧

作用:为数据提供描述数据

概要

系统注解:
  * 内置注解
    * @Deperated
    * @Overrride
    * @SuppressWarnings
  * 元注解
    * @Rentention 
    * @Target
    * @Inhrited
    * @Documented
@Deperated
* 用来标记一个方法,类,或者属性已经过期
@Override
* 用来标记一个方法是重载父类的, 会到他的上层或者上上层去寻找, 知道找到位置
@SupressWarning

源码:

@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    String[] value();
}
让编译器忽略一些提醒,比如过时的方法等

元注解

用来标注注解类的注解,可以用于自定义注解
@Retention
注解什么时候可见, 分为(运行时可见,.class 及源码中可见 , 源码可见)

源码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE})
public @interface Retention {
    RetentionPolicy value();
}

添加注解时的参数类型为RetentionPolicy

public enum RetentionPolicy {
    CLASS,  //.class 或者源码中可见
    RUNTIME,  //运行时可见,可以通过反射获得
    SOURCE;  //仅在源码中可见

    private RetentionPolicy() {
    }
}
@Target
用于标记该注解适用于什么类型的元素(类,方法,变量等)

添加注解时的参数类型是ElementType

public enum ElementType {
    ANNOTATION_TYPE, //用于注解其他注解
    CONSTRUCTOR,
    FIELD,
    LOCAL_VARIABLE,
    METHOD,
    PACKAGE,  //该注解用于注解包声明
    PARAMETER,
    TYPE; //标示该注解用于注解类,接口,枚举类型

    private ElementType() {
    }
}
@Inhrited
表明被它修饰的注解具有继承性
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedAnnotation {
}
class A{
    @InheritedAnnotion
    classB{}
    classC extends ClassB{}
    public void static print(){
      system.out.println(ClassC.class.isAnnotationPresent(InheritedAnnotation.class));
    }
}

最终 print 方法输出结果为true

@Documented

直接在需要加入到JavaDoc的地方加上该注解即可
上一篇 下一篇

猜你喜欢

热点阅读