Domanda

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;
È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top