2012-04-30 61 views
17

可能是愚蠢的問題,但我怎麼能通過null方法需要longint如何將null傳遞給期望long或int的方法?

例子:

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

現在,我怎麼傳遞null兩個methos:

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

想法,建議?

+1

爲什麼要空傳遞給這樣的方法?你期望它做什麼? –

回答

31

問題是intlong是原語。您無法將null轉換爲原始值。

你當然可以使用包裝類IntegerLong,而不是longint在你的方法簽名。

+9

所以,簡短的回答:你不能。 –

2

你不能那樣做。 Java中原始類型不能爲null

如果你想通過null你有你的方法簽名更改爲

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

你不能 - 有沒有這樣的價值。如果您可以更改方法簽名,您可以改爲使用引用類型。 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 
} 
+0

不能更改該方法,因爲基於該方法存在緊密耦合的實現。 – Rachel

+5

@Rachel:那麼你不能傳遞null,就像那樣簡單。 「int」有2^32個值 - 你試圖引入一個額外的值。 「int」值中沒有足夠的位來表示它。 –

+0

@JonSkeet:是的,我將不得不改變我的一些設計,以使我在調用此函數之前進行空檢查。 – Rachel

3

使用包裝類:

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

您可以將null轉換爲非基元包裝類,它將被編譯。

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

但是,執行時會拋出NullPointerException。沒有多大幫助,但是知道可以將包裝等效爲傳遞一個將基元作爲參數的方法是有用的。

4

根據您擁有多少種此類方法以及多少次呼叫,您有另一種選擇。

您可以編寫包裝方法(N.B.),而不是在您的代碼庫中分發空檢查。,不是類型包裝(INT =>整數),但其中的方法包裹你的):

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

鑄字的值以Long如下面將會使編譯錯誤消失,但最終將在NullPointerException結束。

testClass.iTakeLong((Long)null) 

一種解決方案是使用代替原始longLong類型。

public void iTakeLong(Long param) { } 

其他的解決方案是使用org.apache.commons.lang3.math.NumberUtils

testClass.iTakeLong(NumberUtils.toLong(null)) 
相關問題