读书人

java三元运算符的bug?

发布时间: 2012-09-19 13:43:53 作者: rapoo

java三元运算符的bug??

以前没有注意到问题,下面的TestCase运行报空指针异常。

?

?

public class A extends TestCase {public void testA() {Integer num = null;assertNull(false ? Integer.valueOf(0) : num);assertNull(false ? 0 : num);}}
?

?

class文件分析:

?

?

false ? Integer.valueOf(0) : num

?

public void testA();  Code:   Stack=1, Locals=3, Args_size=1   0:   aconst_null   1:   astore_1   2:   aload_1   3:   astore_2   4:   return

?

vs

?

false ? 0 : num

?

public void testA();  Code:   Stack=1, Locals=3, Args_size=1   0:   aconst_null   1:   astore_1   2:   aload_1   3:   invokevirtual   #15; //Method java/lang/Integer.intValue:()I   6:   invokestatic    #21; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;   9:   astore_2   10:  return

?

总结:由于三元运算符导致,由于num为null,转为int时会出错。这算不算JDK6的bug?

?

读书人网 >编程

热点推荐