Cannot Select Parameterized Type

I want to create a rest to communicate between server and client.

The constructor given below:

public class RestHelper<I, R> {
    public RestHelper(String url, I input, Class<R> output){
        ResponseEntity<R> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, output );
    }
}

For normal type, I can do:

RestHelper<User, Result> helper = new RestHelper<>(url, user, Result.class);

How can I pass a generic type, like:

ResultContainData<Boolean>

The code below is not working:

    ResultContainData<Boolean> result = new ResultContainData<>();
    RestHelper<User, ResultContainData<Boolean>> helper = new RestHelper<>(url, user, (Class<ResultContainData<Boolean>>) ((ParameterizedType) result.getClass().getGenericSuperclass()).getActualTypeArguments()[0]);

I got a runtime error: cannot cast to ParameterizedType.

3

2 Answers

I got the solution.

ResultContainData<Boolean> result = new ResultContainData<>();
RestHelper<User, ResultContainData<Boolean>> helper = new RestHelper<>(url, user, (Class<ResultContainData<Boolean>>)result.getClass());

It's working for me. I am still looking for a better solution.

1

You can only learn the value of I and R by capturing them in a subclass definition - otherwise they are erased at runtime. Ex:

class MyStringRestHelper extends RestHelper<String, String> {

Then using something like my TypeTools you can resolve the values of I and R:

Class<?>[] typeArgs = TypeResolver.resolveRawArguments(RestHelper.class, MyStringRestHelper.class);
Class<?> i = typeArgs[0];
Class<?> r = typeArgs[1];
assert i == r == String.class;

Your Answer

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

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest