I need a service lookup method that returns a compatible service. These particular services are (non-generic) subclasses of the same generic superclass, and I’d like to use generics to assure compatibility.
Classes:
class BaseDTOclass AaaDTO extends BaseDTOclass BbbDTO extends BaseDTOinterface BaseService<T extends BaseDTO>interface AaaService extends BaseService<AaaDTO>interface BbbService extends BaseService<BbbDTO>
What generics definitions must I put into the placeholders in the resolver class below? I want to express that resolve() returns a service implementation that is compatible to the given object.
public class Resolver {
@Autowired private AaaService aaaService;
@Autowired private BbbService bbbService;
public <T ???> BaseService<???> resolve(T object) {
if (object instanceof AaaDTO) {
return (???) aaaService;
} else if (object instanceof BbbDTO) {
return (???) bbbService;
} else {
throw new IllegalArgumentException();
}
}
}
Simply said I want to tell the compiler that the following is safe:
BaseDTO dto = getDtoFromSomewhereElse();
resolver.resolve(dto).foo(dto);
If your method foo is defined in
BaseServiceas follows:You could do the following: