Dereference may produce 'java.lang.NullPointerException'
This question already has an answer here:
Take a look at this example taken from here
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;
}
}
}
}
The bytecodes generated by javac for the argue() method are shown below:
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
As you can see for switch statement with String data type a tableswitch is done, and for each case the value passed to switch is compared with the case's value, so what this means is that in your case extras.getString
can be called multiple times without your previous if
checks being called, and as such since extras is a bundle there is a chance it might get dereferenced and cause a nullpointer exception.
It's always a good practice to create a local variable instead of doing multiple calls of the method, you can have a look at this presentation by Jake Wharton to understand why.
链接地址: http://www.djcxy.com/p/90482.html上一篇: 装配x86中的斐波纳契系列