2

Whenwriting a JAXWS client, thisis what I have used in the past:

// CALL SERVICE
EPaymentsService bPayService = new EPaymentsService();
ServiceInterface stub = bPayService.getPort();
BindingProvider bp = (BindingProvider) stub;
Map<String, Object> rc = bp.getRequestContext();
String endPointUrl = propFile.getString(Constants.END_POINT_URL);
rc.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endPointUrl);
// RESPONSE
ResponseMessage resMessage = stub.sendMessage(reqMessage);

In my code, ServiceInterface does not extend BindingProvider.So how come we dont get an error while casting

BindingProvider bp = (BindingProvider) stub;
Victor
  • 16,609
  • 71
  • 229
  • 409

1 Answers1

6
BindingProvider bp = (BindingProvider) stub;

This is a narrowing reference conversion. According to one of the rules of Narrowing reference conversion, an interface type K can be assigned to a non-parameterized interface type J, provided K is not a sub-type of J(you wouldn't require an explicit cast if K were a sub-type of J).

J j = (J) K;

If the cast fails, a ClassCastException is thrown at runtime.

InputStream in = System.in;
Runnable r = (Runnable) in;

The above snippet compiles because both InputStream and Runnable are non-parameterized interfaces, but would result in a ClassCastException at run-time.

A cast from ServiceInterface to BindingProvider works because getPort returns a dynamic proxy class that implements the WSBindingProvider interface, which in turn extends the BindingProvider interface.

c.P.u1
  • 16,664
  • 6
  • 46
  • 41
  • Thanks. I guess it is like converting an Integer to a Float? Or is it the reverse? – Victor Jul 15 '13 at 14:54
  • No, bro. It's not like that. You cannot cast an `Integer` to `Float` or vice-versa because they are both class types. But you can assign a `Float` or `Integer` to `Number` without any cast since they extend `Number`. – c.P.u1 Jul 15 '13 at 15:58
  • The specification of this (i.e. that the Proxy, which is returned by the method javax.xml.ws.Service#getPort, MUST implement interface javax.xml.ws.BindingProvider) is found in section 4.2.3 of the JAX-WS specification, currently downloadable from http://jcp.org/en/jsr/detail?id=224. – Mikko Östlund Dec 11 '14 at 13:27