注解(Annotation)

Annotation——注解

comment——注释

一、 什么是注解

JDK5.0引入

  • 作用

    • 不是程序本身,可以对程序作出解释(同comment)
    • 可以被其他程序(如编译器)读取
  • 格式

    • @注释名+(参数)

      @SuppressWarnings(value="unchecked")
      
      image-20201203185129939 image-20201203185334616
  • 使用场景

    • 相当于额外的辅助信息

      image-20201203185239632
    • 通过反射机制实现对这些内置数据的访问

二、 内置注解

image-20201203190021767
  • SuppressWarnings

    image-20201203191000110 image-20201203191031788

三、元注解

meta-annotation——元注解

负责注解其他注解

java.lang.annotation包中

  • @Target——用于描述注解可以在哪里使用

  • @Retention——描述注解的声明周期

    • SOURCE(源码) < CLASS(类) < RUNTIME(运行时-默认
  • @Documented——文档注释javadoc

  • @Inherited

    image-20201203193331074
    @MyAnnotation
    public class Test02 {
    
        @MyAnnotation
        public void test() {
    
        }
    }
    
    //定义一个注解
    //Target——表示注解可以使用的范围
    @Target(value = {ElementType.METHOD,ElementType.TYPE})//类与方法有效
    
    //Retention——表示注解什么地方有效——SOURCE源码、RUNTIME运行时有效、CLASS编译有效
    @Retention(value = RetentionPolicy.CLASS)//运行时有效
    
    //Document——表示是否将注解生成在JAVAdoc中
    @Documented
    
    //Inherited——表示子类可以继承父类的注解
    @Inherited
    @interface MyAnnotation {
    
    }
    

四、自定义元注解

@interface
  • 多个参数

    public class Test03 {
        
    	//如果没有default,在用注解的时候要填写参数,name、age、id、bohhy都要填写完整
        //name定义了default默认值,也可以显示定义name = "小明"
        @MyAnnotation1(name = "小明",id = 101)
        void test() {
    
        }
    
    }
    
    //自定义注解
    @Target(value = ElementType.METHOD)
    @Retention(value = RetentionPolicy.RUNTIME)
    @interface MyAnnotation1{
        String name() default "";
        int age() default 0;
        int id() default -1;
        String[] hobby() default {"唱歌","跳舞"};
    }
    
  • 如果只有一个参数

    public class Test03 {
    
        @MyAnnotation2(100)//2.在使用的时候可以省略参数名如:id = 101
        void test() {
    
        }
    
    }
    
    //自定义注解
    @Target(value = ElementType.METHOD)
    @Retention(value = RetentionPolicy.RUNTIME)
    @interface MyAnnotation2{
        int value() default 0;//1.将唯一的一个参数命名为value
    }
    
posted @ 2020-12-10 20:33  球球z  阅读(103)  评论(0)    收藏  举报