注解

注解

注解
  what?
  注解是JDK1.5之后的新特性,用于为程序提供额外的功能。注解本质就是一个标记,注解本身不具备任何功能,通常它的功能要有反射来实现。

2.注解的作用
   1.为编译器提供相关信息,例如@Override、@FunctionInterface
   2.为软件工具提供相关信息,可用于生成代码、生成文档等时候提供信息:例如@Param、@Return、@Author、@Document
   3.为程序运行提供相关信息:@Conrtroller、@Service、@Value

3.注解的分类
  1.内置注解:@Override、@FunctionalInterface、@Param、@Return、@Author
  2.元注解:用于修饰注解的注解
  @Target:用来描述注解可以写在哪些地方
  @Retention:
      RetentionPolicy.SOURCE:存放在java文件中,可以被编译器读取
      RetentionPolicy.CLASS:存放在.class文件中,可以被虚拟机读取
      RetentionPolicy.RUNTIME:可以程序运行时被反射获取
  @Repeatable:表示注解可重复使用
  @Inherited:表示这个注解是继承于哪个注解类
  3.自定义注解

4.自定义注解的使用
public @interface 注解名{}
package com.blb.demo;

import java.lang.annotation.*;

@Documented    //表示该注解可以出现在doc文档中
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})      //用来描述注解可以写在哪些地方
@Retention(RetentionPolicy.RUNTIME)   //该注解的信息是存储在源代码中,还是class文件中,还是运行时可读取
public @interface MyAnnotation {
}
package com.blb.demo;

@MyAnnotation
public class Demo1 {
    @MyAnnotation
    String name;

    @MyAnnotation
    public void test(String a) {
        int age = 0;
    }
}
package com.blb.demo2;


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

@Target(ElementType.TYPE)    //该注解只能用在
@Retention(RetentionPolicy.RUNTIME)
public @interface Annotation1 {

    String value() default "默认注解内容";
}
package com.blb.demo2;
//@Annotation1
@Annotation1(value = "这是覆盖内容")
public class Demo1 {
    public static void main(String[] args) {
        //获取class对象
        Class<Demo1> class1 = Demo1.class;
        //获取类上面的@Annotation1注解对象(如果没有该注解,则为null)
        Annotation1 annotation1 = class1.getAnnotation(Annotation1.class);
        if (annotation1!=null){
            System.out.println(annotation1.value());
            System.out.println("hello annotation");
        }
    }
}
posted @ 2022-08-03 16:19  熙月希  阅读(62)  评论(0)    收藏  举报