Java 注解特性学习

注解

RAP001 2021年10月31日

内置注解

  1. @Override 重载

  2. @Deprecated 不赞成使用

  3. @SuppressWarnings() 镇压警告

    • @SuppressWarnings(“all”)
    • @SuppressWarnings(“unchecked”)
    • @SuppressWarnings(value={“unchecked”,“deprecation”})
//内置注解
public class BuildInAnnotation01 {
//  @Override 重载
//  @Deprecated 不赞成使用
//  @SuppressWarnings() 镇压警告
//    @SuppressWarnings(“all”)
//    @SuppressWarnings(“unchecked”)
//    @SuppressWarnings(value={“unchecked”,“deprecation”})
//  ”all“,"unchecked"

    public static void main(String[] args) {
        BuildInAnnotation01 buildInAnnotation01 = new BuildInAnnotation01();
        buildInAnnotation01.outPut();  //废弃的

    }

    @Override
    public String toString(){
        return super.toString();
    }

    @Deprecated
    public void outPut(){
        System.out.println("这是已经废弃的");
    }

    @SuppressWarnings("all")
    public void test(){
        //未使用
        List list = new ArrayList(10);
    }

}

元注解

什么是元注解

对注解起定义作用的注解。

四种元注解

  1. @Target: 该注解可以放在哪些对象上面

    • METHOD:方法;
    • TYPE:类,接口,枚举类型;
    • FIELD:域;等等;
    • 其余可见@Target源代码
  2. @Retention: 需要在编译的什么时间保留该注解信息

    SOURCE < CLASS < RUNTIME

  3. @Document: 该注解将包含在javadoc中

  4. @Inherited: 子类可以继承父类的该注解

注解的定义

//定义一个注解
//作用在什么对象上面
@Target(value = {ElementType.METHOD,
        ElementType.TYPE,
        ElementType.FIELD,
        ElementType.CONSTRUCTOR})
//在什么期间还有效
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation{
    //值,一个默认写value
    String value();
}

注解的放置

@MyAnnotation("class")
public class MetaAnnotation02 {
    @MyAnnotation("field")
    private int num;

    @MyAnnotation("method")
    public static void main(String[] args) {
    }

    @MyAnnotation("constructor")
    public MetaAnnotation02() {
    }

    public MetaAnnotation02(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
}
posted @ 2021-10-31 23:36  Rabianp  阅读(29)  评论(0)    收藏  举报