I have been working on Google AdWords and came across this code
adwords-api-6.4.0, com.google.api.adwords.lib.AdWordsUser
public <T extends java.rmi.Remote> T getService(AdWordsService service) throws ServiceException {
try {
return (T) AdWordsServiceFactory.generateSerivceStub(service, this,
service.getEndpointServer(this.isUsingSandbox()), false);
} catch (ClassCastException e) {
throw new ServiceException("Cannot cast serivce. Check the type of return-capture variable.", e);
}
}
which is invoked like this:
AdWordsUser user = new AdWordsUser();
AdGroupServiceInterface adGroupService = user.getService(AdWordsService.V200909.ADGROUP_SERVICE);
Could you please explain how generics work in getService method? How is the return type determined?
What is the purpose of such usage? It doesn’t seem like it provides type safety.
Does this usage have a specific name (so I could find more info on it and change the question title)?
A compiler may often infer the return type from the calling context. In the example provided, the compiler infers that the generic type is
AdGroupServiceInterfacebecause the result is being assigned to that type. If no context is available from which the return type can be inferred, it must be specified explicitly:However, the
getServicemethod is not type-safe. Even though it contains a cast, this is only ensuring that the result implements thejava.rmi.Remoteinterface. Because of type erasure in Java generics, the exact typeTis not known, and the cast can’t check to make sure that the result isAdGroupServiceInterface.That’s why a compiler will warn about the unsafe cast—a
ClassCastExceptionwill be raised when the result is assigned to theAdGroupServiceInterfacevariable, not inside the method and its catch block.