注釋是元數(shù)據(jù)的形式,其中它們提供關(guān)于不是程序本身的一部分的程序的數(shù)據(jù)。注釋對(duì)它們注釋的代碼的操作沒有直接影響。
注釋主要用于以下原因 -
編譯器信息 -編譯器可以使用注釋來檢測(cè)錯(cuò)誤或抑制警告。
編譯時(shí)和部署時(shí)處理 -軟件工具可以處理注釋信息以生成代碼,XML文件等。
運(yùn)行時(shí)處理 -一些注釋可以在運(yùn)行時(shí)檢查。
在Groovy中,基本注釋如下所示:
@interface - at符號(hào)字符(@)向編譯器指示以下是注釋。
注釋可以以沒有主體的方法的形式和可選的默認(rèn)值來定義成員。
注釋可以應(yīng)用于以下類型 -
單行注釋以//開頭,并且能在行的任何位置。從//開始,到一行結(jié)束,都被認(rèn)為是注釋的部分。
// a standalone single line comment
println "hello" // a comment till the end of the line
多行注釋以/*開頭,并且能在行的任何位置 。以/*開頭,包括新的行,直到第一個(gè)*/結(jié)束都被認(rèn)為是注釋的部分。多行注釋可以放于聲明的開始或者聲明的中間。
/* a standalone multiline comment
spanning two lines */
println "hello" /* a multiline comment starting
at the end of a statement */
println 1 /* one */ + 2 /* two */
下面給出了字符串注釋的一個(gè)例子 -
@interface Simple { String str1() default "HelloWorld"; }
enum DayOfWeek { mon, tue, wed, thu, fri, sat, sun } @interface Scheduled { DayOfWeek dayOfWeek() }
@interface Simple {} @Simple class User { String username int age } def user = new User(username: "Joe",age:1); println(user.age); println(user.username);
使用注釋時(shí),需要至少設(shè)置所有沒有默認(rèn)值的成員。下面給出一個(gè)例子。當(dāng)定義后使用注釋示例時(shí),需要為其分配一個(gè)值。
@interface Example { int status() } @Example(status = 1)
Groovy中注釋的一個(gè)很好的特性是,你也可以使用閉包作為注釋值。因此,注釋可以與各種各樣的表達(dá)式一起使用。
下面給出一個(gè)例子。注釋Onlyif是基于類值創(chuàng)建的。然后注釋應(yīng)用于兩個(gè)方法,它們基于數(shù)字變量的值向結(jié)果變量發(fā)布不同的消息。
@interface OnlyIf { Class value() } @OnlyIf({ number<=6 }) void Version6() { result << 'Number greater than 6' } @OnlyIf({ number>=6 }) void Version7() { result << 'Number greater than 6' }
這是groovy中注釋的一個(gè)非常有用的功能。有時(shí)可能有一個(gè)方法的多個(gè)注釋,如下所示。有時(shí)這可能變得麻煩有多個(gè)注釋。
@Procedure @Master class MyMasterProcedure {}
在這種情況下,您可以定義一個(gè)元注釋,它將多個(gè)注釋集中在一起,并將元注釋應(yīng)用于該方法。所以對(duì)于上面的例子,你可以使用AnnotationCollector來定義注釋的集合。
import groovy.transform.AnnotationCollector @Procedure @Master @AnnotationCollector
一旦完成,您可以應(yīng)用以下元注釋器到該方法 -
import groovy.transform.AnnotationCollector @Procedure @Master @AnnotationCollector @MasterProcedure class MyMasterProcedure {}
更多建議: