2013-06-03 20 views
-3

我在審覈新的項目代碼。我發現以下行:這些方法在java中與「和」以及「和」是什麼?

crudService.findByNamedQueryFirstResult("TableA.findby.custid", with(
       "custID", IndividulaID).and("flags", custflags).parameters()) 

我在任何類中都看不到方法「with」和「and」。而不是字符串連接。 我知道一個JPQ查詢使用and和。但是如何通過上面的參數?

有人可以幫忙嗎?

+4

您可以告訴他們不是關鍵字,因爲他們需要參數。所以這些都是方法。它們可能在與crudservice相同的jar中定義。 – greedybuddha

+4

另外,請檢查[靜態導入](http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html) – DannyMo

回答

2

在Java中沒有withand關鍵字。這些都是方法調用。

這裏,with()方法通過靜態導入(請參閱@ damo的註釋)導入並創建構建器類的實例; and()方法是返回this;然後.parameters()類將構建該類,並返回調用方法實際需要的內容。這是一個古典建築模式。

靜態導入可用於提高可讀性效果。考慮mockito。要麼你寫:

Mockito.when(xxx).then(xxx); 

或:

import static org.mockito.Mockito.*; 

// the compiler know where `when()` comes from 
when(xxx).then(xxx); 

通用模式爲這樣的構造被稱爲流暢的界面。要完成答案,我只是點什麼,我爲我的項目之一進行:

ProcessorSelector<IN, OUT> selector = new ProcessorSelector<IN, OUT>(); 

selector = selector.when(predicate1).then(p1) 
    .when(predicate2).then(p2) 
    .otherwise(defaultProcessor); 

final Processor<IN, OUT> processor = selector.getProcessor(); 

ProcessorSelector類有一個when()方法;此方法返回另一個類其上有一個then()方法;並且then()方法再次返回ProcessorSelector,其具有when()等。最後,otherwise()方法返回ProcessorSelector,其上有一個.getProcessor()返回Processor

相關問題