2
在學習編寫Web服務的異步客戶端時,我遇到了這段代碼。我想了解如何在這裏使用"new AsyncHandler<Inventory>() {...}"
。我是比較新的Java和有一些我不明白幾件事情:如何在Java中的異步Web服務客戶端代碼中理解AsyncHandler的這種用法?
- 異步處理是
javax.xml.ws.AsyncHandler
,以及如何庫存,一個本地或自定義對象可以成爲其中的一部分。AsyncHandler<Inventory>
是什麼意思? - 是否使用「new
AsyncHandler<Inventory>() {...}
」類的實例化或實現AsyncHandler? - 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
}
}
}
}