Annotation

Use

  • 给compiler提供信息,用来检测错误,如@override
  • 在编译期,一些工具(如apt)可以通过Annotation信息来生成一些代码
  • 在运行期间,可以用来检测,如@NonNull

Declaring an Annotation Type

For Example:

先定义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();
}

使用:

@ClassPreamble (
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)

Predefined Annotation Types

Annotation Types Used by the Java Language

下面三个Annotation在java.lang中被定义

  • @Deprecated 标记的元素是不推荐使用的,使用会产生warning。如果声明了@Deprecated,应该给出弃用的理由以及用什么替代
  • @SuppressWarnings 不产生warning
  • @Override

Annotations That Apply to Other Annotations

下面的Annotations在java.lang.annotation被定义,用来“修饰”其他Annotation。

  • @Rentation 指示被其修饰的Annotation如何被存储:
    • Source:被compiler忽略,只保留在Java Source Code这个层面
    • Class:在编译期被保留,被JVM忽略
    • Runtime:在运行期被保留
  • @Target 表明被其修饰的Annotation作用的区域,有MethodTypeCONSTRUCTOR
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容