解引用可能会产生'java.lang.NullPointerException'

这个问题在这里已经有了答案:

  • 来自getExtras()的NullPointerException 3个答案

  • 看看这里的例子

    class Argument {
    
        public final static int TOMAYTO = 0;
        public final static int TOMAHTO = 1;
    
        static void argue() {
    
            int say = TOMAYTO;
    
            while (true) {
    
                switch (say) {
    
                case TOMAYTO:
    
                    say = TOMAHTO;
                    break;
    
                case TOMAHTO:
    
                    say = TOMAYTO;
                    break;
                }
            }
        }
    }
    

    下面显示了由javac为argue()方法生成的字节码:

       0 iconst_0 // Push constant 0 (TOMAYTO)
       1 istore_0 // Pop into local var 0: int say = TOMAYTO;
       2 iload_0 // Push key for switch from local var 0
                              // Perform switch statement: switch (say) {...
                              // Low case value is 0, high case value is 1
                              // Default branch offset will goto 2
       3 tableswitch 0 to 1: default=2
                0: 24 // case 0 (TOMAYTO): goto 24
                1: 29 // case 1 (TOMAHTO): goto 29
    
                              // Note that the next instruction starts at address 24,
                              // which means that the tableswitch took up 21 bytes
      24 iconst_1 // Push constant 1 (TOMAHTO)
      25 istore_0 // Pop into local var 0: say = TOMAHTO
      26 goto 2 // Branch unconditionally to 2, top of while loop
      29 iconst_0 // Push constant 1 (TOMAYTO)
      30 istore_0 // Pop into local var 0: say = TOMAYTO
      31 goto 2 // Branch unconditionally to 2, top of while loop
    

    正如你所看到的使用String数据类型的switch语句,一个tableswitch已经完成,并且对于每种情况,传递给switch的值将与case的值进行比较,所以这意味着在你的情况下,可以多次调用extras.getString你之前的if调用被调用,因为extras是一个bundle,所以它有可能被取消引用并导致nullpointer异常。

    创建一个局部变量而不是多次调用这个方法总是一个很好的习惯,你可以看一看杰克沃顿的这个演示来理解原因。

    链接地址: http://www.djcxy.com/p/90481.html

    上一篇: Dereference may produce 'java.lang.NullPointerException'

    下一篇: Spring Web MVC: no request body possible for HTTP DELETE anymore