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的工作原理吗?
这与instanceof
无关。方法Long.getLong()
不解析字符串,它返回具有该名称的系统属性的内容,解释为long。由于没有名称为23的系统属性,因此返回null。你想要Long.parseLong()
l1 instanceof Long
因为l1
为null,所以instanceof产生错误(由Java languange规范指定)
l2 instanceof Long
因为你使用了错误的方法getLong
,这会产生错误:
Determines the long value of the system property with the specified name.
Long.getLong(..)
返回系统属性的long值。它会返回null
,因为没有名为“23”的系统属性。所以:
null
,instanceof
在比较空值时返回false
java.lang.Long
(你可以通过输出l3.getClass()
检查)所以true
是预期的而不是使用Long.getLong(..)
,使用Long.parseLong(..)
来解析String
。
我想有人可以将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
。
将检查被检查对象的类型。
在你的前两个将具有null值,它返回false。第三个具有返回true的Long对象。
你可以在这个java词汇表网站上获得有关instaceof的更多信息:http://mindprod.com/jgloss/instanceof.html
长l1 = null; //默认为false对于instanceof,null为false
Long l2 = Long.getLong(“23”); //如果systeme属性中存在“23”,则为true,否则为false
Long l3 = Long.valueOf(23); // true,因为23是long的实例