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

后端 未结 9 458
你的背包
你的背包 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条回答
  •  猫巷女王i
    2020-12-12 13:06

    Since Java 8 new feature Optional you should not use @Nullable or @Notnull in your own code anymore. Take the example below:

    public void printValue(@Nullable myValue) {
        if (myValue != null) {
            System.out.print(myValue);
        } else {
            System.out.print("I dont have a value");
    }
    

    It could be rewritten with:

    public void printValue(Optional myValue) {
        if (myValue.ifPresent) {
            System.out.print(myValue.get());
        } else {
            System.out.print("I dont have a value");
    }
    

    Using an optional forces you to check for null value. In the code above, you can only access the value by calling the get method.

    Another advantage is that the code get more readable. With the addition of Java 9 ifPresentOrElse, the function could even be written as:

    public void printValue(Optional myValue) {
        myValue.ifPresentOrElse(
            v -> System.out.print(v),
            () -> System.out.print("I dont have a value"),
        )
    }
    

提交回复
热议问题