JavaTutorial之Annotation

作用:

  • Information for the compiler (给编译器提供信息):编译器可以使用注释来检测错误或抑制警告。
  • Compile-time and deployment-time processing(编译和部署阶段的一些处理)软件工具可以处理注释信息以生成代码、XML文件等。
  • Runtime processing(运行时的一些处理)有些注释可以运行的时候被检查。

每个注释通常出现在自己的行中。

Declaring an Annotation Type(声明批注类型

Annotation格式:

@interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}

要使注释信息出现在JavaDoc生成的文档中加@Documented,格式如下:

// import this to use @Documented
import java.lang.annotation.*;

@Documented
@interface ClassPreamble {

   // Annotation element definitions
   
}

Predefined Annotation Types(预定义注释类型
三种预定义的注释:

@Deprecated, @Override, @SuppressWarnings.

@Deprecated 格式如下:

   // Javadoc comment follows
    /**
     * @deprecated
     * explanation of why it was deprecated
     */
    @Deprecated
    static void deprecatedMethod() { }
}

@deprecated进行废弃原因说明。

@Override

  // mark method as a superclass method
   // that has been overridden
   @Override 
   int overriddenMethod() { }

While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.(虽然重写方法时不需要使用此注释,但它有助于防止错误。如果标记为@Override的方法无法正确重写其某个超类中的方法,编译器将生成一个错误。

@SuppressWarnings(忽略警告

   // use a deprecated method and tell 
   // compiler not to generate a warning
   @SuppressWarnings("deprecation")
    void useDeprecatedMethod() {
        // deprecation warning
        // - suppressed
        objectOne.deprecatedMethod();
    }

忽略多种警告:
@SuppressWarnings({“unchecked”, “deprecation”})

@SafeVarargs:应用于方法或构造函数时,断言代码不会对其varargs参数执行潜在的不安全操作。使用此批注类型时,将抑制与varargs用法相关的未选中警告。

@FunctionalInterface:@JavaSE8中引入的FunctionInterface注释表示类型声明是一个功能接口,如Java语言规范所定义的那样。

Annotations That Apply to Other Annotations(作用于其他Annotation的Annotation)

@Retention

  • RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.标记的注释仅保留在源代码级别,编译器将忽略它。
  • RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).标记的注释在编译时由编译器保留,但被Java虚拟机(JVM)忽略。
  • RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.JVM保留标记的注释,以便运行时环境可以使用它。

@Documented

  • @Documented annotation indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.)表示每当使用指定的注释时,应该使用Javadoc工具记录这些元素(默认情况下,注释不包括在Javadoc中。)

@Target
在这里插入图片描述

@Inherited
@Inherited annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class’ superclass is queried for the annotation type. This annotation applies only to class declarations.
可以从超类继承注释类型

@Repeatable

Type Annotations and Pluggable Type Systems

For example, you want to ensure that a particular variable in your program is never assigned to null; you want to avoid triggering a NullPointerException. You can write a custom plug-in to check for this. You would then modify your code to annotate that particular variable, indicating that it is never assigned to null. The variable declaration might look like this(例如,您希望确保程序中的某个特定变量从未赋值为null;您希望避免触发NullPointerException。您可以编写一个自定义插件来检查这一点。然后修改代码以注释该特定变量,表明该变量从未赋值为null。变量声明可能如下所示:):

@NonNull String str;

Repeating Annotations
you are writing code to use a timer service that enables you to run a method at a given time or on a certain schedule, similar to the UNIX cron service. Now you want to set a timer to run a method, doPeriodicCleanup, on the last day of the month and on every Friday at 11:00 p.m. To set the timer to run, create an @Schedule annotation and apply it twice to the doPeriodicCleanup method. The first use specifies the last day of the month and the second specifies Friday at 11p.m., as shown in the following code example(您正在编写代码以使用计时器服务,该服务使您能够在给定的时间或按照特定的时间表运行方法,类似于UNIX cron服务。现在,您需要设置一个计时器来运行一个方法doPeriodicCleanup,在每月的最后一天和每周五的11:00 p.m。要将计时器设置为运行,请创建一个@Schedule注释并将其应用于doPeriodicCleanup方法两次。第一种用法指定一个月的最后一天,第二种用法指定星期五晚上11点,如下面的代码示例所示):

@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour="23")
public void doPeriodicCleanup() { ... }

两个步骤:
步骤1:声明可重复的注释类型
The value of the @Repeatable meta-annotation, in parentheses, is the type of the container annotation that the Java compiler generates to store repeating annotations. In this example, the containing annotation type is Schedules, so repeating @Schedule annotations is stored in an @Schedules annotation.

import java.lang.annotation.Repeatable;

@Repeatable(Schedules.class)//containing annotation 
public @interface Schedule {
  String dayOfMonth() default "first";
  String dayOfWeek() default "Mon";
  int hour() default 12;
}

Step 2: Declare the Containing Annotation Type

public @interface Schedules {
    Schedule[] value();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值