关于instanceof工作的问题

问题描述 投票:5回答:6
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

我无法理解返回的输出。我期待第二和第三个系统的真正至少。有人能解释一下instanceof的工作原理吗?

java instanceof
6个回答
15
投票

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


11
投票

l1 instanceof Long

因为l1为null,所以instanceof产生错误(由Java languange规范指定)

l2 instanceof Long

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

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


7
投票

Long.getLong(..)返回系统属性的long值。它会返回null,因为没有名为“23”的系统属性。所以:

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

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


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


0
投票

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

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

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


0
投票

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

Long l2 = Long.getLong(“23”); //如果systeme属性中存在“23”,则为true,否则为false

Long l3 = Long.valueOf(23); // true,因为23是long的实例

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.