问题描述
在第33行中重新声明Integer'a'时,为什么jshell将引用变量显示为Integer的实例(请参阅第38和39行)?重新声明后,第34行显示'a'设置为null.当在第6行中声明"a"但未赋予值,或在第22行中将其重置为null时,"a"不被视为Integer的实例.我希望当引用变量被重新声明时,由于其值为null,因此它不会是类型的实例;但是,事实并非如此.
When redeclaring Integer 'a' in line 33, why does jshell show the reference variable as an instance of Integer (refer to lines 38 & 39)? After the redeclaration, line 34 shows that 'a' is set to null. When 'a' is declared in line 6 but not given a value, or reset to null in line 22, 'a' is not considered an instance of Integer. I would expect that when the reference variable is redeclared, since its value is null, that it would not be an instance of a type; however, that is not the case.
01: java-lava:~ cafedude$ jshell
02: | Welcome to JShell -- Version 11
03: | For an introduction type: /help intro
04:
05: jshell> Integer a;
06: a ==> null
07: | created variable a : Integer
08:
09: jshell> a instanceof Integer;
10: $2 ==> false
11: | created scratch variable $2 : boolean
12:
13: jshell> a = 1;
14: a ==> 1
15: | assigned to a : Integer
16:
17: jshell> a instanceof Integer;
18: $4 ==> true
19: | created scratch variable $4 : boolean
20:
21: jshell> a = null;
22: a ==> null
23: | assigned to a : Integer
24:
25: jshell> a instanceof Integer;
26: $6 ==> false
27: | created scratch variable $6 : boolean
28:
29: jshell> a = 1;
30: a ==> 1
31: | assigned to a : Integer
32:
33: jshell> Integer a;
34: a ==> null
35: | modified variable a : Integer
36: | update overwrote variable a : Integer
37:
38: jshell> a instanceof Integer;
39: $9 ==> true
40: | created scratch variable $9 : boolean
推荐答案
问题是,尽管它说它设置为null,但实际上不是.有关更多详细信息,请参见在bug中添加的注释.
The problem is that, though it says it is set to null, it actually isn't. See added comments in bug for more detail.
我已将错误标题更改为: JShell:应重新声明已声明的变量
I've changed the bug title to: JShell: Redeclared variable should be reset
我将尝试在JDK 12中修复.
I'll attempt to fix in JDK 12.
第二个问题不是bug,Java不允许instanceof运算符不能为真-行为与javac完全匹配.
The second issue is not a bug, Java does not allow instanceof operators that cannot be true -- behavior matches javac exactly.
这篇关于在jshell-11中,为什么重新声明为零的重新声明的引用变量仍然具有类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!