How to avoid null checking in Java?

后端 未结 30 4170
失恋的感觉
失恋的感觉 2020-11-21 04:43

I use object != null a lot to avoid NullPointerException.

Is there a good alternative to this?

For example I often use:



        
30条回答
  •  清歌不尽
    2020-11-21 05:35

    If you use (or planning to use) a Java IDE like JetBrains IntelliJ IDEA, Eclipse or Netbeans or a tool like findbugs then you can use annotations to solve this problem.

    Basically, you've got @Nullable and @NotNull.

    You can use in method and parameters, like this:

    @NotNull public static String helloWorld() {
        return "Hello World";
    }
    

    or

    @Nullable public static String helloWorld() {
        return "Hello World";
    }
    

    The second example won't compile (in IntelliJ IDEA).

    When you use the first helloWorld() function in another piece of code:

    public static void main(String[] args)
    {
        String result = helloWorld();
        if(result != null) {
            System.out.println(result);
        }
    }
    

    Now the IntelliJ IDEA compiler will tell you that the check is useless, since the helloWorld() function won't return null, ever.

    Using parameter

    void someMethod(@NotNull someParameter) { }
    

    if you write something like:

    someMethod(null);
    

    This won't compile.

    Last example using @Nullable

    @Nullable iWantToDestroyEverything() { return null; }
    

    Doing this

    iWantToDestroyEverything().something();
    

    And you can be sure that this won't happen. :)

    It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.

    In IntelliJ IDEA 10.5 and on, they added support for any other @Nullable @NotNull implementations.

    See blog post More flexible and configurable @Nullable/@NotNull annotations.

提交回复
热议问题