目录

Groovy - 注释(Annotations)

Annotations是元数据的一种形式,其中它们提供关于不是程序本身的一部分的程序的数据。 注释对它们注释的代码的操作没有直接影响。

注释主要用于以下原因 -

  • Information for the compiler - Information for the compiler可以使用注释来检测错误或抑制警告。

  • Compile-time and deployment-time processing - 软件工具可以处理注释信息以生成代码,XML文件等。

  • Runtime processing - 可以在运行时检查某些注释。

在Groovy中,基本注释如下所示 -

@interface - 符号字符(@)向编译器指示后面的内容是注释。

注释可以the form没有实体和可选默认值的方法the form定义成员。

注释可以应用于以下类型 -

字符串类型

下面给出了字符串注释的示例 -

@interface Simple { 
   String str1() default "HelloWorld"; 
}

枚举类型

enum DayOfWeek { mon, tue, wed, thu, fri, sat, sun } 
@interface Scheduled {
   DayOfWeek dayOfWeek() 
} 

class类型

@interface Simple {} 
@Simple 
class User {
   String username
   int age
}
def user = new User(username: "Joe",age:1); 
println(user.age); 
println(user.username);

注释成员值

使用注释时,至少需要设置所有没有默认值的成员。 下面给出一个例子。 在定义后使用注释示例时,需要为其分配值。

@interface Example {
   int status() 
}
@Example(status = 1)

闭包注释参数

Groovy中注释的一个很好的特性是你也可以使用闭包作为注释值。 因此,注释可以与各种表达一起使用。

下面给出一个例子。 注释Onlyif是基于类值创建的。 然后将注释应用于两个方法,这两个方法根据数字变量的值将不同的消息发布到结果变量。

@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中注释的一个非常有用的功能。 有时可能会有一个方法的多个注释,如下所示。 有时,如果有多个注释,这可能会变得混乱。

@Procedure 
@Master class 
MyMasterProcedure {} 

在这种情况下,您可以定义一个元注释,它将多个注释结合在一起,并将元注释应用于该方法。 因此,对于上面的示例,您可以使用AnnotationCollector定义注释集合。

import groovy.transform.AnnotationCollector
@Procedure 
@Master 
@AnnotationCollector

完成此操作后,您可以将以下元注释器应用于该方法 -

import groovy.transform.AnnotationCollector
@Procedure 
@Master 
@AnnotationCollector
@MasterProcedure 
class MyMasterProcedure {}
Groovy - XML.下一篇>
↑回到顶部↑
WIKI教程 @2018