Java高级_注解

@SafeVarargs

挺有意思的一个注解

@SafeVarargs 这是1.7 之后新加入的基本注解. 如例所示,当使用可变数量的参数的时候,而参数的类型又是泛型T的话,就会出现警告。 这个时候,就使用@SafeVarargs来去掉这个警告

@SafeVarargs注解只能用在参数长度可变的方法或构造方法上,且方法必须声明为static或final,否则会出现编译错误。一个方法使用@SafeVarargs注解的前提是,开发人员必须确保这个方法的实现中对泛型类型参数的处理不会引发类型安全问题。

1
2
3
4
5
6
7
public class User {

@SafeVarargs
public static <T> T getData(T... ds) {
return ds.length > 0 ? (T) ds[0] : null;
}
}

自定义注解

创建

1
2
3
4
5
6
7
@Target({ ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyNote {
String name() default "zhw";
}

使用自定义注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@MyNote(name = "zhwzhw")
class Util {}

public class NoteTest {

public static void main(String[] args) {
test1();
}

public static void test1() {
//反射获取注解
MyNote myNote = Util.class.getAnnotation(MyNote.class);
// 获取方法
String name = myNote.name();
System.out.println(name);
}
}

结果:

zhwzhw

相信刚刚接触的人一定很茫然

那么接下来讲解一下其中的元注解

元注解

元注解

@Target
@Retention
@Inherited
@Documented
@Repeatable (java1.8 新增)

有这么五种

@Target

@Target 表示这个注解能放在什么位置上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Target({ 
// 能修饰包
ElementType.PACKAGE,
// 能修饰类、接口或枚举类型
ElementType.TYPE,
ElementType.TYPE_USE,
ElementType.TYPE_PARAMETER,
// 能修饰构造器
ElementType.CONSTRUCTOR,
// 能修饰方法
ElementType.METHOD,
// 能修饰成员变量
ElementType.FIELD,
// 能修饰局部变量
ElementType.LOCAL_VARIABLE,
// 能修饰参数
ElementType.PARAMETER,
// 能修饰注解
ElementType.ANNOTATION_TYPE})

@Retention

表示生命周期

只能选择一个生命周期

下面是错误的写法,只是方便说明而已

1
2
3
4
5
6
7
@Retention({
// 注解在java文件编程成.class文件后,依然存在,但是运行起来后就没了
RetentionPolicy.CLASS,
// 注解在运行起来之后依然存在,程序可以通过反射获取这些信息
RetentionPolicy.RUNTIME,
// 注解只在源代码中存在,编译成class之后,就没了
RetentionPolicy.SOURCE})

@Inherited

表示该类有继承性

@Documented

在用javadoc命令生成API文档后,该文档里会出现该注解说明

@Repeatable

当没有@Repeatable修饰的时候,注解在同一个位置,只能出现一次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Names {
FileType[] value();
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Repeatable(Names.class)
public @interface FileType {
String value();
}
@FileType( ".java" )
@FileType( ".html" )
@FileType( ".css" )
@FileType( ".js" )
public void work(){

}

小唠嗑:

本章到这里就结束了,谢谢耐心看到这里的各位Boss,如果觉得有哪里说的不好的地方,还请高抬贵手多多原谅,不惜指教。

最后,谢谢!

---本文结束感谢您的阅读!---