Groovy注解
在其他地方翻译为注释,而且我看的很迷糊,因此只能看看官网,需要的道友可以去看一下官方文档 http://docs.groovy-lang.org/docs/groovy-3.0.2/html/documentation/中1.4.1中的Meta-annotations
一、作用
编译器信息 -编译器可以使用注释来检测错误或抑制警告。
编译时和部署时处理 -软件工具可以处理注释信息以生成代码,XML文件等。
运行时处理 -一些注释可以在运行时检查。
基本注释如下所示:
@interface - at符号字符(@)向编译器指示以下是注释。
注释可以以没有主体的方法的形式和可选的默认值来定义成员。
二、定义注解
成员返回值可以有字符串、枚举、注解、数组、类
@interface SomeAnnotation {
String value()
}
@interface SomeAnnotation {
String value() default 'something'
}
@interface SomeAnnotation {
int step()
}
@interface SomeAnnotation {
Class appliesTo()
}
@interface SomeAnnotation {}
@interface SomeAnnotations {
SomeAnnotation[] value()
}
enum DayOfWeek { mon, tue, wed, thu, fri, sat, sun }
@interface Scheduled {
DayOfWeek dayOfWeek()
}
三.注解用法
可以用在变量、类、方法
@SomeAnnotation
void someMethod() {
// ...
}
@SomeAnnotation
class SomeClass {}
@SomeAnnotation String var
四.设置注解的作用域
@Target([ElementType.METHOD, ElementType.TYPE])
其中@Target用于设置注解的作用域,如上面设置注解用于方法和类型,不能用于其他地方(注意:TYPE不能用于java8)
五.注解参数接受闭包
需要将成员返回值设置为类
@interface OnlyIf {
Class value()
}
完整示例
class Runner {
static <T> T run(Class<T> taskClass) {
def tasks = taskClass.newInstance()
def params = [jdk:6, windows: false]
tasks.class.declaredMethods.each { m ->
if (Modifier.isPublic(m.modifiers) && m.parameterTypes.length == 0) {
def onlyIf = m.getAnnotation(OnlyIf)
if (onlyIf) {
Closure cl = onlyIf.value().newInstance(tasks,tasks)
cl.delegate = params
if (cl()) {
m.invoke(tasks)
}
} else {
m.invoke(tasks)
}
}
}
tasks
}
}
5.元注释可用于减少涉及多个注释的代码的大小
@Service
@Transactional
class MyTransactionalService {}
定义元注释
@Service
@Transactional
@AnnotationCollector
@interface TransactionalService {
}
第一段代码可以替换为
@TransactionalService
class MyTransactionalService {}
6.注解参数的覆盖
创建两个注解@Foo 和@Bar,还有一个元注解@FooBar
@Retention(RetentionPolicy.RUNTIME)
public @interface Foo {
String value()
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Bar {
String value()
}
@Foo
@Bar
@AnnotationCollector
public @interface FooBar {}
测试
@Foo('a')
@Bar('b')
class Bob {}
assert Bob.getAnnotation(Foo).value() == 'a'
println Bob.getAnnotation(Bar).value() == 'b'
覆盖 会将包含的两个注解@Foo和@Bar的参数都变为同一个,当然需要两个参数的类型一样,示例如下:
@FooBar('a')
class Joe {}
assert Joe.getAnnotation(Foo).value() == 'a'
println Joe.getAnnotation(Bar).value() == 'a'
查询类的注解的参数
类名.getAnnotation(注解名称).value()