三目运算以及自动拆箱导致的NPE
System.out.println(false ? 1 : (Long)null); // NPE System.out.println(false ? Long.valueOf(1L) : (Long)null); System.out.println(false ? 1 : (String) null);
使用 javap -v 查看字节码可以看到
9: invokevirtual #35 // Method java/lang/Long.longValue:()J 12: invokevirtual #39 // Method java/io/PrintStream.println:(J)V 15: getstatic #21 // Field java/lang/System.out:Ljava/io/PrintStream; 18: aconst_null 19: checkcast #33 // class java/lang/Long 22: invokevirtual #27 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V 25: getstatic #21 // Field java/lang/System.out:Ljava/io/PrintStream; 28: aconst_null 29: checkcast #42 // class java/lang/String 32: invokevirtual #27 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V
可以看到 " false ? 1 : (Long)null" 中对应的关键的代码 Long.longValue(); 正式由于自动拆箱的操作导致了NPE;
当三目运算条件为false时,当":"左侧为基本数据类型,而右侧为基本类型的包装类型时,则会引发包装类型的自动拆箱操作;(这句话更完整的解释为,当根据条件判断时,如果选择的表达式为基本类型的包装类型,而未被选择的表达式为基本类型,则选择的结果会自动进行拆箱操作); 因此当 ((Long)null).longValue()被执行时则会抛出NPE
以下是官方文档的解释
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25
If one of the operands is of type T, where T is
Byte
,Short
, orCharacter
, and the other operand is a constant expression (§15.28) of typeint
whose value is representable in the type U which is the result of applying unboxing conversion to T, then the type of the conditional expression is U.