有关自定义Null-Safety注释的信息来自Kotlin官方:
https://kotlinlang.org/docs/reference/java-interop.html
我的Java代码:
@TypeQualifierNickname
@javax.annotation.Nonnull(when = When.ALWAYS)
@Retention(RetentionPolicy.RUNTIME)
public @interface NN {
}
@NN
public static <T> T notNull(@Nullable T nullable, String message) throws NullPointerException {
return Objects.requireNonNull(nullable, message);
}
错误调用:
fun max(comparator: Comparator<in T>): T {
val maxOrNull: T? = ...
// IDEA error:
// Type mismatch.
// Required: T
// Found: T?
return Require.notNull(maxOrNull, "Collection is empty.")
}
但是,如果我将@NN
替换为@org.jetbrains.annotations.NotNull
,则没有错误:
@org.jetbrains.annotations.NotNull
public static <T> T notNull(@Nullable T nullable, String message) throws NullPointerException {
return Objects.requireNonNull(nullable, message);
}