提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
Target的ElementType成员详解
前言
深入Target的源码了解Target如何使用
提示:以下是本篇文章正文内容,下面案例可供参考
一、ElementType是什么?
//ElementType是Target注解的内容
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();
}
二、ElementType是干什么的
ElementType用来指定Target的目标作用范围
1.ElementType的内容
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
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
2.ElementType的详解
使用方法:@Target(ElementType.成员)
Element.TYPE :能够修饰类、接口或者枚举类型
Element.FIELD :能够修饰成员变量
Element.METHOD :能够修饰方法
Element.PARAMETER :能够修饰参数(例如@RequestBody)
Element.CONSTRUCTOR :能够修饰构造器
Element.LOCAL_VARIABLE :能够修饰局部变量
Element.ANNOTATION_TYPE :能够修饰注解
Element.PACKAGE :能够修饰包
Element.TYPE_PARAMETER
Element.TYPE_USE
Java8前注解只能标注在一个声明(如字段、类、方法)上。
Java8后,新增的TYPE_PARAMETER可以用于标注类型参数,
而TYPE_USE则可以用于标注任意类型(不包括class)。
//本文仅作Target的参考代码 其他注释例如@Retention @Documented 等均已省略
@Target(ElementType.PARAMETER)
public @interface RequestBody {
/**
* Whether body content is required.
* <p>Default is {@code true}, leading to an exception thrown in case
* there is no body content. Switch this to {@code false} if you prefer
* {@code null} to be passed when the body content is {@code null}.
* @since 3.2
*/
}
# 总结
以上就是今天要讲的内容,本文仅仅简单介绍了Target的使用,而ElementType提供了大量能使我们快速便捷地处理目标作用范围。