小编Rob*_*len的帖子

相等检查后使用 Long 的 NullPointerException

这让我很震惊。

如果您有一个 Java Long 变量,并且使用 == 运算符检查与原始值的相等性,则该值的运行时类型将更改为原始 long。

随后检查变量是否为空值,然后抛出意外的 NullPointerException。

所以在测试类中:

public class LongDebug {

public static void main(String[] args) {
    Long validValue = 1L; 
    Long invalidValue = -1L;
    Long nullValue = null;

    System.out.println("\nTesting the valid value:");
    testExpectedBehaviour(validValue);
    testUnExpectedBehaviour(validValue);

    System.out.println("\nTesting the invalid value:");
    testExpectedBehaviour(invalidValue);
    testUnExpectedBehaviour(invalidValue);

    System.out.println("\nTesting the null value:");
    testExpectedBehaviour(nullValue);
    testUnExpectedBehaviour(nullValue);
}

/**
 * @param validValue
 */
private static void testExpectedBehaviour(Long value) {
    if (value == null || value == -1) System.out.println("Expected: The value was null or invalid");
    else System.out.println("Expected: …
Run Code Online (Sandbox Code Playgroud)

java casting nullpointerexception long-integer

5
推荐指数
1
解决办法
1万
查看次数