Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...