2014-05-04 13 views
2

在學習編寫Web服務的異步客戶端時,我遇到了這段代碼。我想了解如何在這裏使用"new AsyncHandler<Inventory>() {...}"。我是比較新的Java和有一些我不明白幾件事情:如何在Java中的異步Web服務客戶端代碼中理解AsyncHandler的這種用法?

  1. 異步處理是javax.xml.ws.AsyncHandler,以及如何庫存,一個本地或自定義對象可以成爲其中的一部分。 AsyncHandler<Inventory>是什麼意思?
  2. 是否使用「new AsyncHandler<Inventory>() {...}」類的實例化或實現AsyncHandler?
  3. handleResponse和AsyncHandler的關係是什麼?

下面是代碼:

public class StockWebServiceClientCallbackMainMyCopy { 
    private static Logger log = Logger.getLogger(StockWebServiceClientCallbackMain.class.getName()); 

    @SuppressWarnings("unchecked") 
    public static void main(String[] args) throws Exception { 
     final Stock stockPort = new StockService().getStockPort(); 
     log.info("Got StockService port successfully"); 

     final int thresh = 2; 
     // TODO: (53.01) Call async method passing in callback method 
     //    In the callback method, print out all the items and exit 
     //    Important: call System.exit() from callback 
     stockPort.getStockItemsWithQuantityLessThanAsync(thresh, new AsyncHandler<Inventory>(){ 
      @Override 
      public void handleResponse(Response<Inventory> response) { 
       log.info("Callback invoked"); 
       try{ 
        Inventory inventory = response.get(); 
        for (Item item : inventory.getItems()){ 
         System.out.println(item.getProductId() + " " + item.getQuantity()); 
        } 
        System.exit(0); 
       } 
       catch(Exception e){ 
        e.printStackTrace(); 
       } 
      }   
     }); 

     // TODO: (53.02) Note simulation of other activity using Thread.sleep() 
     while (true){ 
      try{ 
       Thread.sleep(1000); 
      } catch (InterruptedException e){ 
       // ok 
      } 
     } 
    } 
} 

回答

0

javax.xml.ws.AsyncHandler是一個接口。你在代碼中做的是創建一個實現這個接口的「匿名」類的實例。

接口(AsyncHandler)定義了一個名爲handleResponse的方法。您在代碼中重寫此方法。

該接口使用可以是任何類型的模板。所以當你實現這個接口時,你需要指定你希望從服務調用返回的對象的類型。