0

I've seen many post on this argument but it's the first time that i use generic/reflection. I want to create some method to wrap JAX-WS call (doPost, doGet etc)

For this purpose, JAX-WS have a method like this:

Integer resp = client.target(url).request().post(Entity.entity(user, MediaType.APPLICATION_JSON), Integer.class);

So it want as last parameter, the "return type".

To do this i've created a class to wrap post mehod:

public class GenericPost<I> {
    public static I doPost(String name, Object entity) {
        String url = Constants.SERVICE_HOST_NAME + method + "/";
        Client client = ClientBuilder.newClient();  
        I resp = client.target(url).request().post(Entity.entity(entity, MediaType.APPLICATION_JSON), /* How i can tell that here i want i.class ?*/);

    return resp;
    }
}

As i have described in the code, how i tell the method that the last parameter is the I (generic) class ?

I would use this method like this:

GenericPost<Integer> postInteger = GenericPost<Integer>.doPost("something", arg);
GenericPost<String> postInteger = GenericPost<String>.doPost("something", arg);

1 Answer 1

2

Create a generic method in a non-generic class, and pass the Class<T> as argument:

public class GenericPost {
    public static <T> T doPost(String name, Object entity, Class<T> clazz) {
        String url = Constants.SERVICE_HOST_NAME + method + "/";
        Client client = ClientBuilder.newClient();  
        T resp = client.target(url).request().post(Entity.entity(entity, MediaType.APPLICATION_JSON), clazz);
        return resp;
    }
}

And use it like this:

Integer postInteger = GenericPost.doPost("something", arg, Integer.class);
String postString = GenericPost.doPost("something", arg, String.class);
Sign up to request clarification or add additional context in comments.

1 Comment

This was what i have suspected... In real, that method is wrapped in another class (i'm using JAVA FX Service). So i pass the argument and all now works in my other class :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.