2

I ran into this piece of code when learning to write an asynchronous client of a web service. I am trying to understand how "new AsyncHandler<Inventory>() {...}" is used here. I am relatively new to Java, and there are a few things that I don't understand:

  1. AsyncHandler is from javax.xml.ws.AsyncHandler, and how Inventory, an local or custom object can be part of it. What does AsyncHandler<Inventory> mean?
  2. Is the use of "new AsyncHandler<Inventory>() {...}" an instantiation or implementation of the class AsyncHandler?
  3. what is the relationship of handleResponse and AsyncHandler?

Here is the code:

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
            }
        }
    }
}
learner
  • 3,092
  • 2
  • 21
  • 33

1 Answers1

0

javax.xml.ws.AsyncHandler is an interface. What you are doing in your code is creating an instance of an "anonymous" class which implements this interface.

The interface (AsyncHandler) defines a single method called handleResponse. You override this method in the your code.

The interface uses a template , which can be any type. So when you implement the interface, you specify the type of the object you expect to get returned from your service call.

Greycon
  • 793
  • 6
  • 19