zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

Switch竟然会报空指针异常,学到了!

2023-03-09 22:08:21 时间

本文转载自微信公众号「月伴飞鱼」,作者日常加油站 。转载本文请联系月伴飞鱼公众号。

前言

前几天重新看 《阿里巴巴Java开发手册》有一条这样的规约:

出于好奇,打算研究一下!,强迫症,没办法!

我们先用一个案例测试一下:

  1. public class Test { 
  2.     public static void main(String[] args) { 
  3.         String param = null
  4.         switch (param) { 
  5.             case "null"
  6.                 System.out.println("匹配null字符串"); 
  7.                 break; 
  8.             default
  9.                 System.out.println("进入default"); 
  10.         } 
  11.     } 

显而易见,如果switch传入空值,会抛空指针!

看到这,我们先可以思考下面几个问题:

  • switch 除了 String 还支持哪种类型?
  • 为什么《阿里巴巴Java开发手册》规定String类型参数要先进行 null 判断?
  • 为什么可能会抛出空指针异常?

下面开始对上面的问题进行分析

问题分析

首先参考官方文档对swtich 语句相关描述。

翻译如下:

switch 的表达式必须是 char, byte, short, int, Character, Byte, Short, Integer, String, 或者 enum 类型,否则会发生编译错误

同时switch 语句必须满足以下条件,否则会出现编译错误:

  • 与 switch 语句关联的每个 case 都必须和 switch 的表达式的类型一致;
  • 如果 switch 表达式是枚举类型,case 常量也必须是枚举类型;
  • 不允许同一个 switch 的两个 case 常量的值相同;
  • 和 switch 语句关联的常量不能为 null ;
  • 一个 switch 语句最多有一个 default 标签。

翻译如下:

switch 语句执行的时候,首先将执行 switch 的表达式。如果表达式为 null, 则会抛出 NullPointerException,整个 switch 语句的执行将被中断。

另外从《Java虚拟机规范》这本书,我们可以学习到:

总结一下就是:

1.编译器使用 tableswitch 和 lookupswitch 指令生成 switch 语句的编译代码。

2.Java 虚拟机的 tableswitch 和 lookupswitch 指令只能支持 int 类型的条件值。如果 swich 中使用其他类型的值,那么就必须转化为 int 类型。

所以可以了解到空指针出现的根源在于:虚拟机为了实现 switch 的语法,将参数表达式转换成 int。而这里的参数为 null, 从而造成了空指针异常。

下面对官方文档的内容采用反汇编方式进一步分析下

不熟悉字节码的,推荐看看美团的这篇文章:https://tech.meituan.com/2019/09/05/java-bytecode-enhancement.html

下面开始硬货!

反汇编看看

一个例子:

  1. public class Test { 
  2.     public static void main(String[] args) { 
  3.         String param = "月伴飞鱼"
  4.         switch (param) { 
  5.             case "月伴飞鱼1"
  6.                 System.out.println("月伴飞鱼1"); 
  7.                 break; 
  8.             case "月伴飞鱼2"
  9.                 System.out.println("月伴飞鱼2"); 
  10.                 break; 
  11.             case "月伴飞鱼3"
  12.                 System.out.println("月伴飞鱼3"); 
  13.                 break; 
  14.             default
  15.                 System.out.println("default"); 
  16.         } 
  17.     } 

反汇编代码得到:

  1. Compiled from "Test.java" 
  2. public class com.zhou.Test { 
  3.   public zhou.Test(); 
  4.     Code: 
  5.        0: aload_0 
  6.        1: invokespecial #1                  // Method java/lang/Object."<init>":()V 
  7.        4: return 
  8.  
  9.   public static void main(java.lang.String[]); 
  10.     Code: 
  11.        0: ldc           #2                  // String 月伴飞鱼 
  12.        2: astore_1 
  13.        3: aload_1 
  14.        4: astore_2 
  15.        5: iconst_m1 
  16.        6: istore_3 
  17.        7: aload_2 
  18.        8: invokevirtual #3                  // Method java/lang/String.hashCode:()I 
  19.       11: tableswitch   { // -768121881 to -768121879 
  20.             -768121881: 36 
  21.             -768121880: 50 
  22.             -768121879: 64 
  23.                default: 75 
  24.           } 
  25.       36: aload_2 
  26.       37: ldc           #4                  // String 月伴飞鱼1 
  27.       39: invokevirtual #5                  // Method java/lang/String.equals:(Ljava/lang/Object;)Z 
  28.       42: ifeq          75 
  29.       45: iconst_0 
  30.       46: istore_3 
  31.       47: goto          75 
  32.       50: aload_2 
  33.       51: ldc           #6                  // String 月伴飞鱼2 
  34.       53: invokevirtual #5                  // Method java/lang/String.equals:(Ljava/lang/Object;)Z 
  35.       56: ifeq          75 
  36.       59: iconst_1 
  37.       60: istore_3 
  38.       61: goto          75 
  39.       64: aload_2 
  40.       65: ldc           #7                  // String 月伴飞鱼3 
  41.       67: invokevirtual #5                  // Method java/lang/String.equals:(Ljava/lang/Object;)Z 
  42.       70: ifeq          75 
  43.       73: iconst_2 
  44.       74: istore_3 
  45.       75: iload_3 
  46.       76: tableswitch   { // 0 to 2 
  47.                      0: 104 
  48.                      1: 115 
  49.                      2: 126 
  50.                default: 137 
  51.           } 
  52.      104: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream; 
  53.      107: ldc           #4                  // String 月伴飞鱼1 
  54.      109: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V 
  55.      112: goto          145 
  56.      115: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream; 
  57.      118: ldc           #6                  // String 月伴飞鱼2 
  58.      120: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V 
  59.      123: goto          145 
  60.      126: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream; 
  61.      129: ldc           #7                  // String 月伴飞鱼3 
  62.      131: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V 
  63.      134: goto          145 
  64.      137: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream; 
  65.      140: ldc           #10                 // String default 
  66.      142: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V 
  67.      145: return 

先介绍一下下面会用到的字节码指令

  • invokevirtual:调用实例方法
  • istore_0 将int类型值存入局部变量0
  • istore_1 将int类型值存入局部变量1
  • istore_2 将int类型值存入局部变量2
  • istore_3 将int类型值存入局部变量3
  • aload_0 从局部变量0中装载引用类型值
  • aload_1 从局部变量1中装载引用类型值
  • aload_2 从局部变量2中装载引用类型值

我们继续看汇编代码:

先看偏移为 8 的指令,调用了参数的 hashCode() 函数来获取字符串 "月伴飞鱼" 的哈希值。

  1. 8: invokevirtual #3                  // Method java/lang/String.hashCode:()I 

接下来我们看偏移为 11 的指令处:

tableswitch 是跳转引用列表, 如果值小于其中的最小值-768121881 或者大于其中的最大值-768121879,跳转到 default 语句。

  1. 11: tableswitch   { // -768121881 to -768121879 
  2.             -768121881: 36 
  3.             -768121880: 50 
  4.             -768121879: 64 
  5.                default: 75 
  6.           } 

其中 -768121881 为键,36 为对应的目标语句偏移量。

hashCode 和 tableswitch 的键相等,则跳转到对应的目标偏移量,"月伴飞鱼"的哈希值806505866不在最小值-768121881和最大值-768121879之间,因此跳转到 default 对应的语句行(即偏移量为 75 的指令处执行)。

月伴飞鱼的hash值计算:("月伴飞鱼").hashCode();

从 36 到 75 行,根据哈希值相等跳转到判断是否相等的指令。

然后调用java.lang.String#equals判断 switch 的字符串是否和对应的 case 的字符串相等。

如果相等则分别根据第几个条件得到条件的索引,然后每个索引对应下一个指定的代码行数。

继续从偏移量75行往下看:

  1. 76: tableswitch   { // 0 to 2 
  2.                0: 104 
  3.                1: 115 
  4.                2: 126 
  5.          default: 137 
  6.     } 

default 语句对应 137 行,打印 “default” 字符串,然后执行 145 行 return 命令返回。

通过 tableswitch 判断执行哪一行打印语句。

总结就是整个流程是先计算字符串参数的哈希值,判断哈希值的范围,然后哈希值相等再判断对象是否相等,然后执行对应的代码块。

这种先判断 hash 值是否相等(有可能是同一个对象/两个对象有可能相等),再通过 equals 比较 对象是否相等 的做法,在 Java 的很多 JDK 源码中和其他框架中也非常常见的。

分析空指针问题

反汇编前言中的代码:

  1. public class Test { 
  2.     public static void main(String[] args) { 
  3.         String param = null
  4.         switch (param) { 
  5.             case "null"
  6.                 System.out.println("匹配null字符串"); 
  7.                 break; 
  8.             default
  9.                 System.out.println("进入default"); 
  10.         } 
  11.     } 
  1. public class com.zhou.Test { 
  2.   public com.zhou.Test(); 
  3.     Code: 
  4.        0: aload_0 
  5.        1: invokespecial #1                  // Method java/lang/Object."<init>":()V 
  6.        4: return 
  7.  
  8.   public static void main(java.lang.String[]); 
  9.     Code: 
  10.        0: aconst_null 
  11.        1: astore_1 
  12.        2: aload_1 
  13.        3: astore_2 
  14.        4: iconst_m1 
  15.        5: istore_3 
  16.        6: aload_2 
  17.        7: invokevirtual #2                  // Method java/lang/String.hashCode:()I 
  18.       10: lookupswitch  { // 1 
  19.                3392903: 28 
  20.                default: 39 
  21.           } 
  22.       28: aload_2 
  23.       29: ldc           #3                  // String null 
  24.       31: invokevirtual #4                  // Method java/lang/String.equals:(Ljava/lang/Object;)Z 
  25.       34: ifeq          39 
  26.       37: iconst_0 
  27.       38: istore_3 
  28.       39: iload_3 
  29.       40: lookupswitch  { // 1 
  30.                      0: 60 
  31.                default: 71 
  32.           } 
  33.       60: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream; 
  34.       63: ldc           #6                  // String 匹配null字符串 
  35.       65: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V 
  36.       68: goto          79 
  37.       71: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream; 
  38.       74: ldc           #8                  // String 进入default 
  39.       76: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V 
  40.       79: return 

可以猜测3392903 应该是 "null" 字符串的哈希值。

  1. 10: lookupswitch  { // 1 
  2.                3392903: 28 
  3.                default: 39 
  4.           } 

我们可以打印其哈希值去印证:System.out.println(("null").hashCode());

总结整体流程:

  1. String param = null
  2. int hashCode = param.hashCode(); 
  3. if(hashCode == ("null").hashCode() && param.equals("null")){ 
  4.  System.out.println("null");  
  5. }else
  6.  System.out.println("default");  

 

因此空指针的原因就一目了然了:调用了 null 对象的实例方法。