Java - Generic Type as parameter of the readEntity method of Jax rs client

Asked

Viewed 216 times

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?

  • 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?

  • 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 just return geradorRetorno.apply(response);. I believe that the call to that function would then become cliente.post(modeloRequisicao, "caminho/método", r -> r.readEntity(RespostaCadastroUsuarioSistema.class));

  • That was beautiful. Thank you. Please prepare an answer.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.