Target的ElementType成员粗略使用及解释

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

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   :能够修饰参数(例如@RequestBodyElement.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提供了大量能使我们快速便捷地处理目标作用范围。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值