使用Annotation功能

在这里插入图片描述

Java中提供了Annotation功能,该功能可用于类、构造方法、成员变量、方法、参数等的声明中。该功能并不影响程序的运行,但是对编译器等辅助工具产生影响。


定义Annotation类型

在定义Annotation类型时,也需要用到用来定义接口的interface关键字,但需要在interface关键字前加一个“@”符号,即定义Annotation类型的关键字为@interface,这个关键字隐含的意思是继承了java.long.annotation.Annotation-接口

public @interface MoreMemberAnnotation {
   
	String value();
	Class type();
}
  • String: 成员类型。可用的成员类型有String、Class、primitive、enumerated和annotation,以及所列类型的数组。
  • value: 成员名称。如果所定义的Annotation类型中只包含一个成员,通常将成员名称命名为value。

在为Annotation类型定义成员时,也可以为成员设置默认值。例如,下面的代码在定义Annotation类型时就为成员设置了默认值。

public @interface MoreMemberAnnotation {
   
	String value() default "默认值";
	Class type() default void.class;
}

在定义Annotation类型时,还可以通过Annotation类型@Target来设置Annotation类型适用的程序元素种类。如果未设置@Target,则表示适用于所有程序元素。枚举类ElementType中的枚举通常用来设置@Target,如下表:

枚举常量 说明
ANNOTATION_TYPE 表示用于Annotation类型
TYPE 用于表示类、接口和枚举,以及Annotation类型
CONSTRUCTOR 表示用于构造方法
FIELD 表示用于成员变量和枚举常量
METHOD 表示用于方法
PARAMETER 表示用于参数
LOCAL_VARIVBLE 表示用于局部变量
PACKAGE 表示用于包

通过Annotation类型@Retention可以设置Annotation的有效范围。枚举类RetentionPolicy中的枚举常量用来设置@Retention,如下表所示。如果未设置@Retention,Annotation的有效范围为枚举常量CLASS表示的范围。

枚举常量 说明
SOURCE 表示不编译Annotation到文件夹中,有效范围最小
CLASS 表示编译Annotation到类文件中
RUNTIME 表示在运行时加载Annotation到JVM中,有效范围最大
package zhao;

import java.lang.annotation.*;

@Target(ElementType.CONSTRUCTOR)
//用于构造方法
@Retention(RetentionPolicy.RUNTIME)
//在运行时加载Annotation到JVM中
public @interface Constructor_Annotation {
   
	String value() default "默认构造方法";//定义一个具有默认值的String型成员
}
package zhao;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

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

//用于字段、方法和参数
@Retention(RUNTIME)
//在运行加载Annotation到JVM中
@Target({
    FIELD, METHOD, PARAMETER })
public @
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值