前言
jsr305是一個規范,具體來說是一套用來給代碼分析工具(如IDEA)檢查代碼缺陷用的注解,類似jsr303(Bean Validation規范)。今天在學習Spring源碼時,發現其中使用到了jsr305中的注解。
Spring中的NonNull注解中使用到了jsr305中的Nonnull注解,可以看做是對Nonnull注解的一個封裝。
IDEA對jsr305注解的支持
引入jsr305和spring核心的maven依賴
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
測試代碼
import org.springframework.lang.NonNull;
public class Client2 {
@NonNull
private static String test() {
return null;
}
}
這種情況IDEA就會有警告,提示方法返回結果可能為null
原理
那么IDEA是如何認識Spring的注解的呢,查找得知,IDEA應該不認識Spring的注解,但它認識jsr305的注解,而Spring注解NonNull中使用到了jsr305的注解javax.annotation.Nonnull類。
/**
* A common Spring annotation to declare that annotated elements cannot be {@code null}.
*
* <p>Leverages JSR-305 meta-annotations to indicate nullability in Java to common
* tools with JSR-305 support and used by Kotlin to infer nullability of Spring API.
*
* <p>Should be used at parameter, return value, and field level. Method overrides should
* repeat parent {@code @NonNull} annotations unless they behave differently.
*/
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Nonnull
@TypeQualifierNickname
public @interface NonNull {
}

可以看到,IDEA本身配置了一些關於代碼分析的注解,其中就包括了jsr305的javax.annotation.Nonnull注解。
自定義檢查注解
我們也可以配置我們自定義的注解。
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyNonnull {
}
將自定義注解添加到配置中

可以看到,自定義注解在代碼中也是生效的。
IDEA對Guava的Beta注解的支持
引入Guava的maven依賴
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
代碼測試
import com.google.common.io.ByteStreams;
public class Client3 {
public static void main(String[] args) {
System.out.println(ByteStreams.nullOutputStream());
}
}
IDEA會有代碼警告,因為ByteStreams的nullOutputStream()方法被@Beta注解修飾。
原理

IDEA本身配置了一些關於不穩定API的注解,只要被這些注解修飾,IDEA就會有代碼提示。
總結
上述兩個功能只是IDEA的代碼檢查提供功能的很小一部分,更多關於IDEA的代碼檢查的信息,可以查看 Code inspections。