1.1 注解和反射--注解

150 阅读2分钟

注解

一、注解入门

AnnotationJDK5.0引入的技术

作用:

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

格式:

  • @注解名在代码中存在,可以添加一些参数
@SuppressWarnings(value="unchecked")

使用:

  • packageclassmethodfield等上面
  • 可以通过反射编程实现对这些元数据的访问

二、内置注解

  • @Override(重写)

只可以用于修饰方法,表示一个方法声明打算重写超类中的另一个方法

public class Annotation1 {
    /**
     * @Override是重写的意思
     * @return
     */
    @Override
    public String toString() {
        return super.toString();
    }
}
  • @FunctionalInterface(函数式接口)
/**
 * @FunctionalInterface 函数式接口
 */
@FunctionalInterface
public interface Runnable {
    public abstract void run();
}
  • @Deprecated(弃用)

此注解可以用于修饰方法、属性、类,表示不鼓励程序员使用这样的元素

@Deprecated
public void destroy() {
    throw new NoSuchMethodError();
}
  • @SupperssWarnings

用来抑制编译时警告信息,需要添加一个参数产能正确使用,这些参数已经定义好,选择使用即可

/**
 * @SuppressWarnings 镇压警告
 */
@SuppressWarnings("all")
public static void test2() {
    // 创建一个元素不使用
    ArrayList<Object> objects = new ArrayList<>();
}

三、自定义注解和元注解

3.1 元注解

元注解就是负责注解其他注解的注解,Java定义了4个标准的meta-annotation类型,其被用来对其他annotation类型进行说明

所在包:java.lang.annotation

四个元注解:

  • @Target:用于描述注解使用范围

  • @Retention:表示需要在什么级别保存注解信息

    • SOURCE < CLASS < RUNTIME
  • @Documented:说明该注解将被包含在javadoc

  • @Inherited:说明子类可以继承父类中该注解

示例:

/**
 * @ClassName Annotation2
 * @Description 测试元注解
 * @Author wangwk-a
 * @Date 2022/1/4 20:56
 * @Version 1.0
 */
@MyAnnotation
public class Annotation2 {

    @MyAnnotation
    public static void test() {

    }
}

/**
 * 定义一个注解
 * @Target 表示注解可以用在哪些地方,ElementType
 * @Retention 表示注解在什么地方还有效,源码 < class < 运行
 * @Documented 表示注解是否生成在JavaDoc中
 * @Inherited 表示子类是否可以继承父类的注解
 * @author wangwk-a
 */
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyAnnotation {

}

3.2 自定义注解

使用@interface自定义注解时,自动继承java.lang.annotation.Annotation接口

分析:

  • @interface用来声明一个注解,格式public @interface 注解名{定义内容}
  • 其中每一个方法实际上是声明了一个配置参数
  • 方法名称就是参数名称
  • 返回值类型就是参数类型(只能是基本类型、ClassStringenum
  • 可以通过default来声明参数的默认值
  • 如果只有一个参数成员,一般参数名为value
  • 注解元素必须要有值,定义注解元素时,经常使用空字符串、0作为默认值
 /**
  * @ClassName Annotation3
  * @Description 自定义注解
  * @Author wangwk-a
  * @Date 2022/1/4 21:09
  * @Version 1.0
  */
 public class Annotation3 {
     /**
      * 使用注解,如果参数没有默认值,就必须要给值
      */
     @MyAnnotation2(name = "nick")
     public static void test() {
     }
 }
 
 /**
  * 自定义注解
  * @author wangwk-a
  */
 @Target({ElementType.TYPE, ElementType.METHOD})
 @Retention(RetentionPolicy.RUNTIME)
 @interface MyAnnotation2 {
     /**
      * 注解的参数:参数类型 + 参数名() default 默认值;
      * 默认值为-1则代表不存在
      */
     String name() default "";
     int age() default 0;
     int id() default -1;
     String[] schools() default {"西工大"};
 }