在项目中,我们总会或多或少接触过一些注解,如常见的@Override,@Autowired。我们分别点进去看一下:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;
}
我们发现它们的类型都是@interface,而且有2个相同的注解@Target和@Retention,这两个注解是我们写新注解时必须要有的注解,它们都是元注解。
元注解
元注解的作用就是注解其他注解,一般我们使用自定义注解时,就需要用元注解来标注我们自己的注解。一共有四个元注解。
@Target
它指定了注解修饰的范围,在哪些作用域上起作用。我们可以看到它里面的参数都是ElementType枚举类。
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
//用于描述类,接口(包括注解类型),或enum声明
TYPE,
/** Field declaration (includes enum constants) */
//用于属性声明(包括enum常量)
FIELD,
/** Method declaration */
//方法声明
METHOD,
/** Formal parameter declaration */
//形式参数声明
PARAMETER,
/** Constructor declaration */
//构造方法声明
CONSTRUCTOR,
/** Local variable declaration */
//局部变量声明(方法内部变量)
LOCAL_VARIABLE,
/** Annotation type declaration */
//注解类型声明,可参见@Taeget注解
ANNOTATION_TYPE,
/** Package declaration */
//包的声明
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
*

本文详细解析Java注解的工作原理,包括@Target、@Retention、@Documented和@Inherited等元注解的使用,以及如何利用自定义注解进行参数校验和实现AOP。同时,介绍了自定义注解在代码校验和切面编程中的具体应用。

6万+

被折叠的 条评论
为什么被折叠?



