在 Java 中如何使用运算符 == 比较对象和原语?

How comparison Object and primitive, with operator == works in Java?

例如:

Long objectLong = 555l;
long primitiveLong = 555l;

System.out.println(objectLong == primitiveLong); // result is true.

是否有调用 objectLong.longValue() 方法来比较 Long 和 long 或其他方式?

一如既往,Java 语言规范是适合参考的资源

来自 JLS 15.21.1(“数值相等运算符 == 和 !=”):

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).

然后从5.6.2(二进制数值提升):

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  • If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
  • [...]

因此 Long 被拆箱为 long。您的代码相当于:

Long objectLong = 555l;
long primitiveLong = 555l;

// This unboxing is compiler-generated due to numeric promotion
long tmpLong = objectLong.longValue();

System.out.println(tmpLong == primitiveLong);