java基础-注解

后端 / 笔记 / 2021-09-25

什么是注解

注解是用了描述类的一些额外信息,可用来标注在,方法,字段上面。

常用注解

  • Override 只能标注在子类覆盖父类的方法上
  • Deprecated 标注在过时的方法或类上面,有提示的作用.
  • SuppressWarnings("unchecked") 标注在编译器认为有问题的类上面,用来镇压警告
    • serial
    • unchecked
    • unused
    • all

元注解

元注解就是,开发人员自己定义的注解时,会使用到的。

  • @Target 指定注解标注的位置
  • @Rentention 指定注解信息保留到什么时候
  • @Inherited 指定注解是否可被子类继承

@Target

// 表示该注解作用在方法和字段上
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Component {
    String path();
}

public enum ElementType {

    TYPE, // 作用在类上(常用)

    FIELD, // 作用在字段上(常用)

    METHOD, // 作用在方法上(常用)

    PARAMETER, // 作用在方法参数上(常用)

    CONSTRUCTOR, // 作用在构造器上

    LOCAL_VARIABLE, // 作用在局部变量上

    ANNOTATION_TYPE, // 作用在注解上(常用)

    PACKAGE, // 作用在包上

    TYPE_PARAMETER, // 作用在方法参数上
    TYPE_USE // 作用在类型上
}

@Rentention

// 表示该注解作用在方法和字段上
@Target({ElementType.METHOD, ElementType.TYPE})
// 保留到程序运行时
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
    String path();
}

public enum RetentionPolicy {

    SOURCE, // 保留在源码文件中

    CLASS, // 保留在class文件中,jvm加载时抛弃。

    RUNTIME // 保留到程序运行时(forever)
}

@Inherited

允许继承

package annotation;

import java.lang.annotation.*;

// 表示该注解作用在方法和字段上
@Target({ElementType.METHOD, ElementType.TYPE})
// 保留到程序运行时
@Retention(RetentionPolicy.RUNTIME)

// 允许继承
@Inherited
public @interface Component {
}


package annotation;

import java.lang.annotation.Inherited;
import java.util.Arrays;

@Component
public class ComponentTest {
    class CustomComponent extends ComponentTest {

    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(Component.class.getAnnotations()));
        System.out.println(Arrays.toString(CustomComponent.class.getAnnotations()));
    }
}

[@java.lang.annotation.Target(value=[METHOD, TYPE]), @java.lang.annotation.Retention(value=RUNTIME), @java.lang.annotation.Inherited()]
[@annotation.Component()]

不允许继承

// 表示该注解作用在方法和字段上
@Target({ElementType.METHOD, ElementType.TYPE})
// 保留到程序运行时
@Retention(RetentionPolicy.RUNTIME)

// 不允许继承
//@Inherited
public @interface Component {
}


package annotation;

import java.lang.annotation.Inherited;
import java.util.Arrays;

@Component
public class ComponentTest {
    class CustomComponent extends ComponentTest {

    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(Component.class.getAnnotations()));
        System.out.println(Arrays.toString(CustomComponent.class.getAnnotations()));
    }
}

[@java.lang.annotation.Target(value=[METHOD, TYPE]), @java.lang.annotation.Retention(value=RUNTIME)]
[]