How to use @Nullable and @Nonnull annotations more effectively?

后端 未结 9 459
你的背包
你的背包 2020-12-12 12:01

I can see that @Nullable and @Nonnull annotations could be helpful in preventing NullPointerExceptions but they do not propag

9条回答
  •  甜味超标
    2020-12-12 13:08

    If you use Kotlin, it supports these nullability annotations in its compiler and will prevent you from passing a null to a java method that requires a non-null argument. Event though this question was originally targeted at Java, I mention this Kotlin feature because it is specifically targeted at these Java annotation and the question was "Is there a way to make these annotations more strictly enforced and/or propagate further?" and this feature does make these annotation more strictly enforced.

    Java class using @NotNull annotation

    public class MyJavaClazz {
        public void foo(@NotNull String myString) {
            // will result in an NPE if myString is null
            myString.hashCode();
        }
    }
    

    Kotlin class calling Java class and passing null for the argument annotated with @NotNull

    class MyKotlinClazz {
        fun foo() {
            MyJavaClazz().foo(null)
        }
    }  
    

    Kotlin compiler error enforcing the @NotNull annotation.

    Error:(5, 27) Kotlin: Null can not be a value of a non-null type String
    

    see: http://kotlinlang.org/docs/reference/java-interop.html#nullability-annotations

提交回复
热议问题