如何将null传递给期望long或int的方法?
可能是愚蠢的问题,但我如何将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
想法,建议?
问题是int
和long
是原始的。 您不能将null
传递给原始值。
您当然可以在方法签名中使用包装类Integer
和Long
而不是long
和int
。
你不能 – 没有这样的价值。 如果您可以更改方法签名,则可以改为使用引用类型。 Java为每个基本类提供了一个不可变的“包装器”类:
class TestClass { public void iTakeLong(Long id); public void iTakeInt(Integer id); }
现在,您可以将空引用或引用传递给包装器类型的实例。 Autoboxing将允许您写:
iTakeInt(5);
在该方法中,您可以编写:
if (id != null) { doSomethingWith(id.intValue()); }
或使用自动拆箱:
if (id != null) { doSomethingWith(id); // Equivalent to the code above }
您可以将null转换为非原始包装类,它将进行编译。
TestClass testClass = new TestClass(); testClass.iTakeLong( (Long)null); // Compiles testClass.iTakeInt( (Integer)null); // Compiles
但是,这将在执行时抛出NullPointerException
。 没有多大帮助,但知道你可以传递相当于包含原语作为参数的方法的包装器是有用的。
根据您拥有的此类方法数量以及呼叫次数,您可以选择其他方式。
您可以编写包装器方法 (NB,不是类型包装器(int => Integer),而是包装您的方法),而不是在整个代码库中分配空检查:
public void iTakeLong(Long val) { if (val == null) { // Do whatever is appropriate here... throwing an exception would work } else { iTakeLong(val.longValue()); } }
使用Wrapper类:
TestClass{ public void iTakeLong(Long id); public void iTakeInt(Integer id); public void iTakeLong(long id); public void iTakeInt(int id); }
你不能这样做。 Java中的原始类型不能为null
。
如果要传递null
,则必须将方法签名更改为
public void iTakeLong(Long id); public void iTakeInt(Integer id);
如下所示将值转换为Long
将使编译错误消失但最终将以NullPointerException
结束。
testClass.iTakeLong((Long)null)
一种解决方案是使用Long
类型而不是原始long
。
public void iTakeLong(Long param) { }
其他解决方案是使用org.apache.commons.lang3.math.NumberUtils
testClass.iTakeLong(NumberUtils.toLong(null))