I have few methods which send request and should return response of specific type. all of the requests extends RequestVO type, and all of the responses extends ResponseVO.
To avoid casting in each method that return response , I have used generic method(see send method below).
After each request sent, even if it has failed, I need to save the response in Database.
The problem is in responseVO = new ErrorResponseVO(e);
, it produces compiler error : Type mismatch: cannot convert from ErrorResponseVO to T
.
How can I avoid this without casting?
@Override
public AuthSignResponseVO authenticate(AuthRequestVO authRequestVO) throws RegulationException{
return send(authRequestVO, AuthSignResponseVO.class);
}
@Override
public AuthSignResponseVO sign(SignRequestVO signRequestVO) throws RegulationException{
return send(signRequestVO, AuthSignResponseVO.class);
}
@Override
public CollectResponseVO collect(CollectRequestVO collectRequestVO) throws RegulationException{
return send(collectRequestVO, CollectResponseVO.class);
}
@Override
public CancelResponseVO cancel(CancelRequestVO cancelRequestVO) throws RegulationException{
return send(cancelRequestVO, CancelResponseVO.class);
}
private <T extends ResponseVO> T send(RequestVO requestVO, Class<T> responseType) throws RegulationException{
HttpHeaders headers = new HttpHeaders();
HttpEntity<RequestVO> httpEntity = new HttpEntity<>(requestVO,headers);
ResponseEntity<T> responseEntity = null;
T responseVO = null;
try{
responseEntity = restTemplate.postForEntity(url, httpEntity, responseType);
responseVO = responseEntity.getBody();
}catch(RestClientException e){
responseVO = new ErrorResponseVO(e);
throw new RegulationException(RegulationResponseCode.GeneralError);
}finally{
//save in db the response
}
return responseVO;
}