如何向期望long或int类型参数的方法传递null?

28

可能是个愚蠢的问题,但我该如何将null传递给接受longint的方法?

示例:

TestClass{
  public void iTakeLong(long id);
  public void iTakeInt(int id);
}

现在我该如何将null传递给这两个方法:

TestClass testClass = new TestClass();
testClass.iTakeLong(null); // Compilation error : expected long, got null
testClass.iTakeInt(null);   // Compilation error : expected int, got null

有什么想法和建议吗?


2
为什么你想要将null传递给这样的方法?你期望它会做什么? - Peter Lawrey
7个回答

51
问题在于intlong是原始数据类型。你不能向原始类型的变量传递null值。
在方法签名中,您可以使用包装类IntegerLong来代替intlong

13
简短回答:无法做到。 - Louis Wasserman

12

你不能这样做 - 没有这样的值。 如果你可以改变方法的签名,可以改为使用引用类型来传参。Java为每个基本数据类型提供了一个不可变的“包装器”类:

class TestClass {
  public void iTakeLong(Long id);
  public void iTakeInt(Integer id);
}

现在你可以传递一个null引用,或者一个包装类型实例的引用。自动装箱将允许你编写:

iTakeInt(5);

在该方法中,您可以编写:

if (id != null) {
    doSomethingWith(id.intValue());
}

或者使用自动拆箱:

if (id != null) {
    doSomethingWith(id); // Equivalent to the code above
}

无法更改该方法,因为已经有基于该方法的紧密耦合的实现。 - Rachel
5
@Rachel:那么你不能传递空值,就是这么简单。对于一个int类型,有2^32个值 - 你正在尝试引入一个额外的值。int类型的位数不足以表示它。 - Jon Skeet
@JonSkeet:是的,我将不得不更改我的设计,以便在调用此函数之前进行空值检查。 - Rachel

8

您可以将null转换为非基本包装类,这将编译。

TestClass testClass = new TestClass();
testClass.iTakeLong( (Long)null); // Compiles
testClass.iTakeInt( (Integer)null);   // Compiles

但是,执行此操作会抛出NullPointerException。虽然没有什么帮助,但知道您可以将包装器等效物传递给以原始类型作为参数的方法可能很有用。


5

根据您有多少这样的方法和调用次数,您还有另一种选择。

不要在您的代码库中分配 null 检查,您可以编写包装器 方法(注意,不是类型包装器(int => Integer),而是包装您的方法):

public void iTakeLong(Long val) {
    if (val == null) { 
        // Do whatever is appropriate here... throwing an exception would work
    } else {
        iTakeLong(val.longValue());
    }
}

3

使用包装类:

 TestClass{
    public void iTakeLong(Long id);
    public void iTakeInt(Integer id);
    public void iTakeLong(long id);
    public void iTakeInt(int id);
 }

2

您无法这样做。在Java中,原始类型不能为null

如果您想传递null,则需要更改方法签名为

public void iTakeLong(Long id);
public void iTakeInt(Integer id);

1
将值转换为Long,如下所示,可以消除编译错误,但最终会导致NullPointerException
testClass.iTakeLong((Long)null)

一种解决方案是使用类型Long而不是原始类型long

public void iTakeLong(Long param) { }

另一种解决方案是使用org.apache.commons.lang3.math.NumberUtils
testClass.iTakeLong(NumberUtils.toLong(null))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接