86 lines
2.6 KiB
Markdown
86 lines
2.6 KiB
Markdown
|
## 注解
|
|||
|
|
|||
|
### @SafeVarargs
|
|||
|
|
|||
|
在声明具有模糊类型(比如:泛型)的可变参数的构造函数或方法时,Java 编译器会报 unchecked 警告。鉴于这些情况,如果程序员断定声明的构造函数和方法的主体不会对其 varargs 参数执行潜在的不安全的操作,可使用 @SafeVarargs 进行标记,这样的话,Java 编译器就不会报 unchecked 警告。
|
|||
|
|
|||
|
先看看 @SafeVarargs 在 Java SE 中的声明:
|
|||
|
|
|||
|
```java
|
|||
|
package java.lang;
|
|||
|
|
|||
|
import java.lang.annotation.*;
|
|||
|
|
|||
|
@Documented
|
|||
|
@Retention(RetentionPolicy.RUNTIME)
|
|||
|
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
|
|||
|
public @interface SafeVarargs {}
|
|||
|
|
|||
|
```
|
|||
|
|
|||
|
由 Java 源代码声明我们了解到:@SafeVarargs 注解,只能用于标记构造函数和方法,由于保留策略声明为 RUNTIME,所以此注解可以在运行时生效。
|
|||
|
|
|||
|
使用的时候要注意:@SafeVarargs 注解,对于非 static 或非 final 声明的方法,不适用,会编译不通过。
|
|||
|
|
|||
|
@SafeVarargs 使用示例如下:
|
|||
|
|
|||
|
```java
|
|||
|
package org.springmorning.demo.javabase.annotation.pre;
|
|||
|
|
|||
|
/**
|
|||
|
* @author 春晨
|
|||
|
* @date 2019/1/19 9:26
|
|||
|
* Copyright ©2019 春晨 https://www.cnblogs.com/springmorning/p/10285780.html
|
|||
|
*/
|
|||
|
public class SafeVarargsAnnotation<S>{
|
|||
|
|
|||
|
private S[] args;
|
|||
|
|
|||
|
//构造函数可以使用@SafeVarargs标记
|
|||
|
@SafeVarargs
|
|||
|
public SafeVarargsAnnotation(S... args){
|
|||
|
this.args = args;
|
|||
|
}
|
|||
|
|
|||
|
//此处不能使用@SafeVarargs,因为此方法未声明为static或final方法,如果要抑制unchecked警告,可以使用@SuppressWarnings注解
|
|||
|
@SuppressWarnings("unchecked")
|
|||
|
//@SafeVarargs
|
|||
|
public void loopPrintArgs(S... args){
|
|||
|
for (S arg : args) {
|
|||
|
System.out.println(arg);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
//final方法可以使用@SafeVarargs标记
|
|||
|
@SafeVarargs
|
|||
|
public final void printSelfArgs(S... args){
|
|||
|
for (S arg : this.args) {
|
|||
|
System.out.println(arg);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
public static void main(String[] args) {
|
|||
|
SafeVarargsAnnotation.loopPrintInfo("A", "B", "C");
|
|||
|
}
|
|||
|
|
|||
|
//static方法可以使用@SafeVarargs标记
|
|||
|
@SafeVarargs
|
|||
|
public static <T> void loopPrintInfo(T ... infos){
|
|||
|
for (T info : infos) {
|
|||
|
System.out.println(info);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
```
|
|||
|
|
|||
|
如果以上把 @SafeVarargs 标记注释掉,在编译时就会报 unchecked 警告:
|
|||
|
|
|||
|
![](assets/1578080-20190119095853997-1722091659.png)
|
|||
|
|
|||
|
加上 @SafeVarargs 注解,警告被抑制:
|
|||
|
|
|||
|
![](assets/1578080-20190119100022568-1102767552.png)
|
|||
|
|
|||
|
> 本文由 [简悦 SimpRead](http://ksria.com/simpread/) 转码, 原文地址 [www.cnblogs.com](https://www.cnblogs.com/springmorning/p/10285780.html)
|