本文思路参考于用大白话聊聊JavaSE -- 自定义注解入门
在写代码时,我们通常会加上一些注释,告诉开发人员这段代码的含义.eg:
/**
* @Description: 输入的Integer必须大于0
* @Author: Yiang37
* @Date: 2021/04/22 23:58:27
* @Version: 1.0
*/
public int checkIn(Integer integer) {
return integer > 0 ? integer : -1;
}
//...
写下的注释,让阅读代码的人了解到了这段代码所做的事情.
当然,注解是写给人看的,那么有没有一种方式,可以让程序知道这段代码想干什么事情呢?
注解,就是写给程序看的一种注释.
// 没错.就是@interface
public @interface Annotation01 {
//...
}
元注解理解为描述注解的注解,元数据理解为描述数据的数据,元类理解为描述类的类…
在JDK中提供了4个标准的用来对注解类型进行注解的注解类(元注解),他们分别是:
所以,在Java中,除了有限的几个固定的"描述注解的注解"以外,所有的注解都是自定义注解。
@Target
@Retention
@Documented
@Inherited
eg: @Target(ElementType.METHOD) : 注解要用在方法上.
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8 //1.8加入
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8 //1.8加入
*/
TYPE_USE
}
@Target(ElementType.TYPE) // 接口、类、枚举、注解
@Target(ElementType.FIELD) // 字段、枚举的常量
@Target(ElementType.METHOD) // 方法
@Target(ElementType.PARAMETER) // 方法参数
@Target(ElementType.CONSTRUCTOR) // 构造函数
@Target(ElementType.LOCAL_VARIABLE) // 局部变量
@Target(ElementType.ANNOTATION_TYPE) // 注解
@Target(ElementType.PACKAGE) // 包
eg: @Retention(RetentionPolicy.RUNTIME) : 我们希望在程序运行的时候,注解发挥作用.就是说,当你的程序跑起来了,电脑才开始阅读这些注解.
@Retention(RetentionPolicy.SOURCE) // 注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
eg:注解中包含一个String和int
public @interface Annotation01 {
String oneStr() default "this is one str";
int onData();
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Annotation01 {
String oneStr() default "this is one str";
int onData();
}
@Annotation01(oneStr = "abc",onData = 1)
public class AnnotationTest01 {
}
上文中,用上注解后,我们好像什么也没做.
只是知道AnnotationTest01这个类上对应着一个@Annotation01的注解,里面有着oneStr = "abc",onData = 1两个字段.
//待完善....
原文:https://www.cnblogs.com/yang37/p/14692138.html