这可能是一个愚蠢的问题,但是我如何将null
传递给接受long
或int
的方法
示例:
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
有什么想法和建议吗?
发布于 2012-05-01 02:58:32
你不能--没有这样的价值。但是,如果您可以更改方法签名,则可以使其采用引用类型。Java为每个原语类提供了一个不可变的“包装器”类:
class TestClass {
public void iTakeLong(Long id);
public void iTakeInt(Integer id);
}
现在,您可以将空引用或引用传递给包装器类型的实例。自动装箱将允许您编写:
iTakeInt(5);
在该方法中,您可以编写:
if (id != null) {
doSomethingWith(id.intValue());
}
或者使用自动拆箱:
if (id != null) {
doSomethingWith(id); // Equivalent to the code above
}
https://stackoverflow.com/questions/10389001
复制相似问题