2013-06-03 26 views
0

我正在寫一個傳輸對象,它只是簡單地將一個對象從web服務映射到我自己的對象:汽車A到汽車B.在java中從一個對象映射到另一個對象(Transfer Object)時忽略空字段?

汽車類具有里程屬性。

CarB.setMileage(CarA.getMileage()); //if the CarA.getMileage() is null, then my setter fails and I get a nullPointerException 

我有50個字段,我是否正確,我只需要在設置我的字段之前寫入50個單獨的檢查?

if (CarA.getMileage() != null) { 
    CarB.setMileage(CarA.getMileage()); 
} 

有沒有辦法避免編寫50分開,如果!=null檢查報表?

+1

向我們顯示您的設置代碼。它必須超過'this.mileage = newVal;' –

+0

你確定'CarA.getMileage()'是'null'而不僅僅是'CarA'。 –

回答

1

稍有常識的,但更好的方法是在bean Class

function String checkForNull(String str){ 

    //check for null and return corresponding 
} 

共同method然後

CarB.setMileage(checkForNull(CarA.getMileage()));

1

可以在CarB創建一個靜態工廠方法:

// carA is of type CarA returned by the web service 
CarB carB = CarB.fromCarA(carA); 

全空支票等會再在那家工廠的方法來進行。示例代碼:

public class CarB 
{ 
    //.... 

    public static CarB fromCarA(final CarA carA) 
    { 
     if (carA == null) 
      throw new NullPointerException("Where is my car???"); 

     final CarB ret = new CarB(); 

     // Supposing CarA returns an Integer... 
     final Integer mileage = carA.getMileage(); 
     if (mileage != null) 
      ret.setMileage(mileage); 

     // etc etc, then 
     return ret; 
    } 

    // etc 
} 
+0

或者,類似地,如果你不想要構造函數,就用'carB.setMileageFromCar(carA)'。 – chessbot

+0

@chessbot是,但這需要一個這樣的方法,你想設置每個屬性... – fge

+0

公平不夠;看起來他的代碼想要設置屬性而不是構建新車;或許就像'carB.setFrom(carA)'。總之,它並沒有太大的區別。 – chessbot

2

嘗試使用推土機映射。這是一個很好的工具,它可以幫助忽略空值。它可以用於編程映射兩個對象並使用XML。如果屬性名稱相同,則不要在兩個對象字段之間指定任何映射。以下是鏈接:

http://dozer.sourceforge.net/documentation/faq.html

+0

不錯的項目,但它看起來像一個大錘在這裏壓扁bug ... – fge

+0

謝謝fge。我認爲OP只是其中一例,可能有更多的案例可以幫助我們的朋友。所以建議它。 –

+0

對於已刪除的答案:請參閱[什麼是可接受的答案?](http://meta.stackexchange.com/a/118694/182862)。在目前的形式下,你的答案不適用於第8點到第12點,所以我發表了一條評論,並低估了它沒有解決問題。 –

相關問題