Java注解

注解 Annotation

什么是注解?

作用:

  • 不是程序本身, 可以对程序作出解释 (类似注释)
  • 可以被其他程序读取 (如编译器)

格式:

  • @注释名, 还可添加参数
    如:@SuppressWarnings(value="unchecked")
    

在哪使用?

  • 附加在 package, class, method, field 等, 相当于添加了额外的辅助信息
  • 可以通过反射机制编程实现对这些元数据的访问

内置注解

  • @Override : 只适用于修饰方法, 表示打算重写超类的方法
  • @Deprecated : 可修饰方法, 属性和类, 表示不鼓励使用
  • @SuppressWarnings
package com.guanxing.annotation;

import java.awt.*;

//什么是注解
public class Test01 extends Object{

    //@Override 重写的注解
    @Override
    public String toString() {
        return super.toString();
    }

    @Deprecated  //不推荐程序员使用,但可以使用.或者存在风险
    public static void testDep(){
        System.out.println("Deprecated");
    }

    @SuppressWarnings("all")  //镇压警告
    public void testSup(){
        List list = new List();
    }

    public static void main(String[] args) {
        testDep();  //依旧可以使用
    }
}

元注解

  • @Target : 用于描述注解的使用范围
  • @Retention : 表示需要在什么级别保存该注释信息, 用于描述注解的生命周期
    • ( SOURCE < CLASS < RUNTIME )
  • @Document : 说明该注解将被包含在 javadoc 中
  • @Inherited : 说明子类可以继承父类中的该注解
package com.guanxing.annotation;

import java.lang.annotation.*;

//测试元注解
public class Test02 {
    @MyAnnotation  //Target定义作用范围有METHOD
    public void test01(){
    }
}

//定义一个元注解
//Target 表示可作用的地方
@Target(value = {ElementType.METHOD, ElementType.TYPE})

//Retention 表示在什么地方有效
@Retention(value = RetentionPolicy.RUNTIME)

//表示是否将注解生成在javadoc中
@Documented

//表示子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}

自定义注解

package com.guanxing.annotation;

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

//自定义注解
public class Test03 {

    //注解定义了参数,就要传参,除非有default默认值
//    @MyAnnotation2(name = "guanxing")
    @MyAnnotation2(name="guanxing")
    public void test(){};
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    //注解的参数:参数类型+名称()
    //参数名为value的话,使用中可以直接赋值
    String name() default "harris";
    int age() default 0;
    int id() default -1;  //如果默认值为-1,代表不存在

    String[] schools() default {"华南理工", "中国人大"};
}
原文地址:https://www.cnblogs.com/straightup/p/14521910.html