0
I want to abstract a post method from my code, using Generic type to facilitate implementation. The code is a Ws client using Jax-rs. The following
public T2 post(T1 requisicao, String path){
javax.ws.rs.client.Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(Cliente.HOST).path(path);
Invocation.Builder invocationBuilder = webTarget.request();
Response response = invocationBuilder
.header("chave",Cliente.CHAVE)
.header("Content-type",Cliente.CONTENT_TYPE)
.header("Accept",Cliente.ACCEPT)
.post(Entity.json(requisicao));
T2 resposta = null;
resposta = response.readEntity((Class<T2>) resposta.getClass());
return resposta;
}
And here how to use the method:
public RespostaCadastroUsuarioSistema cadastraUsuarioSistema(RequisicaoCadastrarUsuarioSistema modeloRequisicao){
Cliente<RequisicaoCadastrarUsuarioSistema,RespostaCadastroUsuarioSistema> cliente = new Cliente<>();
return cliente.post(modeloRequisicao, "caminho/para/o/metodo");
}
For obvious reasons, the code above Nullpointexception. The problem is that I couldn’t think of a way to make it work, since I can’t instantiate a T2 class because it’s generic and the javax readEntity method. Ws. rs. core. Response does not accept Generic type as parameter.
Do you know if it is possible? Or I will have to work with interface and cast the return method?
Why don’t you pass the class that the method should return as an argument to the method?
– Felipe Marinho
It worked, but I understand that the Generic type is just so you don’t have to do it. I have passed the class twice, in the client class definition (T2) and in the parameter. There is no other way?
– Eric Silva
Are you using Java 8? If so, I think a functional output would be much more appropriate. Something like
public <A,R> R post(A requisicao, String path, Function<Response, R> geradorRetorno)
, and in the final block I would have justreturn geradorRetorno.apply(response);
. I believe that the call to that function would then becomecliente.post(modeloRequisicao, "caminho/método", r -> r.readEntity(RespostaCadastroUsuarioSistema.class));
– Jefferson Quesado
That was beautiful. Thank you. Please prepare an answer.
– Eric Silva