Java 无法选择参数化类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27000227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cannot select Parameterized Type
提问by Michael
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.
我收到一个运行时错误:无法转换为 ParameterizedType。
回答by Michael
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.
它对我有用。我仍在寻找更好的解决方案。
回答by Jonathan
You can only learn the value of I and R by capturing them in a subclass definition - otherwise they are erased at runtime. Ex:
您只能通过在子类定义中捕获它们来了解 I 和 R 的值 - 否则它们会在运行时被删除。前任:
class MyStringRestHelper extends RestHelper<String, String> {
Then using something like TypeToolsyou can resolve the values of I and R:
然后使用类似TypeTools 的东西,你可以解析 I 和 R 的值:
Class<?>[] typeArgs = TypeResolver.resolveRawArguments(RestHelper.class, MyStringRestHelper.class);
Class<?> i = typeArgs[0];
Class<?> r = typeArgs[1];
assert i == r == String.class;