先看引用类型的代码:
import java.util.HashMap;
import java.util.Map;
public class trycatchefinally {
public static void main(String[] args) {
System.out.println(getMap().get("KEY"));
}
public static Map<String, String> getMap() {
Map<String, String> map = new HashMap<>();
map.put("KEY", "INIT");
try {
map.put("KEY", "TRY");
System.out.println("111>>> ");
return map;
} catch (Exception e) {
map.put("KEY", "CATCH");
} finally {
System.out.println("222>>> ");
map.put("KEY", "FINALLY");
map = null;
System.out.println("333>>> ");
}
System.out.println("444>>> ");
return map;
}
}
finally里修改map为null
下面是字节码:
0 new #8 <java/util/HashMap>
3 dup
4 invokespecial #9 <java/util/HashMap.<init>>
7 astore_0
8 aload_0
9 ldc #4 <KEY>
11 ldc #10 <INIT>
13 invokeinterface #11 <java/util/Map.put> count 3
18 pop
19 aload_0
20 ldc #4 <KEY>
22 ldc #12 <TRY>
24 invokeinterface #11 <java/util/Map.put> count 3
29 pop
30 aload_0
31 astore_1
32 aload_0
33 ldc #4 <KEY>
35 ldc #13 <FINALLY>
37 invokeinterface #11 <java/util/Map.put> count 3
42 pop
43 aconst_null
44 astore_0
45 aload_1
46 areturn
47 astore_1
48 aload_0
49 ldc #4 <KEY>
51 ldc #15 <CATCH>
53 invokeinterface #11 <java/util/Map.put> count 3
58 pop
59 aload_0
60 ldc #4 <KEY>
62 ldc #13 <FINALLY>
64 invokeinterface #11 <java/util/Map.put> count 3
69 pop
70 aconst_null
71 astore_0
72 goto 91 (+19)
75 astore_2
76 aload_0
77 ldc #4 <KEY>
79 ldc #13 <FINALLY>
81 invokeinterface #11 <java/util/Map.put> count 3
86 pop
87 aconst_null
88 astore_0
89 aload_2
90 athrow
91 aload_0
92 areturn
下面是注释了try里的return比较生成的不同的字节码:
参考:https://stackoverflow.com/questions/4625650/object-reference-set-to-null-in-finally-block
再看看值类型:
总结如下:
try{ return } finally{…} return
finally修改基本类型,则不影响返回值
finally修改非基本类型,影响返回值