5
Long l1 = null;
Long l2 = Long.getLong("23");
Long l3 = Long.valueOf(23);

System.out.println(l1 instanceof Long);  // returns false
System.out.println(l2 instanceof Long);  // returns false
System.out.println(l3 instanceof Long);  // returns true

我无法理解返回的输出。我期待真正的至少第 2 和第 3 syso 的。有人可以解释 instanceof 是如何工作的吗?

4

6 回答 6

16

这与instanceof. 该方法Long.getLong()不解析字符串,它返回具有该名称的系统属性的内容,解释为 long。由于没有名称为 23 的系统属性,因此它返回 null。你要Long.parseLong()

于 2010-01-28T11:06:48.150 回答
11

l1 instanceof Long

因为l1nullinstanceof产生false(由 Java 语言规范指定)

l2 instanceof Long

这会产生错误,因为您使用了错误的方法getLong

Determines the long value of the system property with the specified name.

于 2010-01-28T11:06:04.700 回答
7

Long.getLong(..)返回系统属性的长值。它null在您的情况下返回,因为没有名为“23”的系统属性。所以:

  • 1 和 2 是null,比较空值时instanceof返回false
  • 3 是java.lang.Long(您可以通过输出检查l3.getClass())所以true是预期的

而不是使用Long.getLong(..),使用Long.parseLong(..)来解析一个String.

于 2010-01-28T11:07:42.153 回答
1

我想可以将 sop 重写为:

System.out.println(l1 != null && l1 instanceof Long);
System.out.println(l2 != null && l2 instanceof Long);
System.out.println(l3 != null && l3 instanceof Long);

一如既往null,不可能是instanceof任何东西。

于 2010-01-28T11:14:26.277 回答
0

的实例将检查被检查对象的类型。

在您中,前两个将具有 null 值,它会返回 false。第三个具有返回 true 的 Long 对象。

您可以在此 java 词汇表站点上获得有关 instaceof 的更多信息:http: //mindprod.com/jgloss/instanceof.html

于 2010-01-28T11:08:24.310 回答
0

长 l1 = null; // 默认为 false null 对于 instanceof 为 false

长 l2 = Long.getLong("23"); //如果“23”存在于具有长值的systeme属性中,则为true,否则为false

长 l3 = Long.valueOf(23); // true 因为 23 是 instanceof Long

于 2019-02-28T11:40:30.813 回答