如何在java泛型中返回类对象“类型”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23413574/
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
How to return a class object "type" in java generics?
提问by arzillo
Imagine to have a java class
想象一下有一个java类
public class FixedClassOfStrings {
List<String> myMember=new ArrayList<String>();
// omissed all non relevant code...
public Class getMyType() {
return String.class;
}
}
How can I make it paramteric, by using java generics?
如何通过使用 java 泛型使其参数化?
My attempts fail:
我的尝试失败了:
public class GenericClass<T> {
List<T> myMember=new ArrayList<T>();
public Class getMyType() {
return T.class; // this gives "Illegal class literal for the type parameter T"
}
}
Also, how can I avoid warning: "Class is a raw type. References to generic type Class should be parameterized" in the FixedClassOsStrings? is it ok to declare:
另外,如何避免在 FixedClassOsStrings 中发出警告:“类是原始类型。对泛型类的引用应该参数化”?可以声明:
public Class<String> getMyType() {
return String.class;
}
...
And if it is ok, what shall I return using generics?
如果没问题,我应该使用泛型返回什么?
public Class<T> getMyType() {
return T.class; // this gives "Illegal class literal for the type parameter T"
}
...
All hints will be appreciated!!!
所有提示将不胜感激!!!
回答by Rogue
I would try something like this:
我会尝试这样的事情:
public Class<T> getMyType() {
return /* some instance of T */.getClass();
}
Alternatively, an easy solution is passing the instance upon construction:
或者,一个简单的解决方案是在构造时传递实例:
public class YourClass<T> {
private final Class<T> type;
public YourClass (/* arguments */, Class<T> type) {
this.type = type;
}
public Class<T> getType() {
return this.type;
}
}