javaSE_8系列博客——Java语言的特性(四)--注解--(2)-- 声明一个注解

来源:互联网 发布:淘宝帐号永久冻结解封 编辑:程序博客网 时间:2024/06/04 20:10

许多注释替换代码中的注释。

假设一个软件组传统上开始每个类的正文,提供重要信息的意见: 

public class Generation3List extends Generation2List {   // Author: John Doe   // Date: 3/17/2002   // Current revision: 6   // Last modified: 4/12/2004   // By: Jane Doe   // Reviewers: Alice, Bill, Cindy   // class code goes here}
要使用注释添加相同的元数据,必须首先定义注释类型。这样做的语法是:


@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();}

注释类型定义看起来类似于接口定义,其中关键字接口前面带有at符号(@)(@ = AT,如注释类型)。注释类型是一种接口形式,将在后面的课程中讨论。目前,您不需要了解界面。 以前注释定义的正文包含注释类型元素声明,它们看起来很像方法。请注意,它们可以定义可选的默认值。 在定义注释类型之后,您可以使用该类型的注释,其中填充的值如下所示:

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

注意:

要使@ClassPreamble中的信息显示在Javadoc生成的文档中,您必须使用@Documented注释来注释@ClassPreamble定义:

// import this to use @Documentedimport java.lang.annotation.*;@Documented@interface ClassPreamble {   // Annotation element definitions   }



阅读全文
0 0