Mistre83
Mistre83

Reputation: 2827

Java - Get current generic class

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);

Upvotes: 0

Views: 105

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213401

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);

Upvotes: 2

Related Questions