英文:
How to create a parametrised type in java with a type variable?
问题
以下是翻译好的部分:
问题的标题可能有些误导,但我不知道如何更好地总结我想要实现的内容。所以请您阅读这篇内容,以理解我想要实现的目标。
我有一个带有类型参数的方法,它会得到某个类(例如 MyClass)。我需要创建一个 Type,表示 List<MyClass>,然后将其返回。
我认为以下代码可以解决我的问题。但实际的行为让我感到惊讶。
public <T> Type getListClass(Class<T> cls) {
Type type = new TypeToken<ArrayList<T>>() {}.getType();
return type;
}
实际代码:
(代码和调试器截图这部分没有提供具体内容)
如果我们检查 type2,我们会发现它的 rawType 是 ArrayList,typeArgument 是 Integer。我希望对于我的泛型类型也是这样的。
但在变量 type 中,我们观察到 rawType 是 ArrayList,typeArgument 是 T。我希望在执行时,T 能够变成一个具体的类(比如 Integer 或 MyCLass)。基本上,我需要一个泛型的 List Type,但在执行点是 具体的。有没有办法实现这一点?
----- 编辑 1 -----
这与此问题不重复:https://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime
那里的答案产生的结果与我的代码相同。
英文:
The question title could be misleading, but I dont know how to summarise better what I want to acomplish. So please read through this body to undestand what I want to achive.
I have a method with a type parameter which gets some Class (eg MyClass). I need to create a Type of List<MyClass> and return it.
I thought this code would solve my problem. But the actual behaviour suprised me.
public <T> Type getListClass(Class<T> cls) {
Type type = new TypeToken<ArrayList<T>>() {}.getType();
return type;
}
Actual code:
Debugger:
I we inspect the type2, we can see that it has the rawType of Arraylist and typeArgument of Integer . Same I want to happen with my generic type.
But in the varibale type we observe a rawType of Arraylist and typeArgument of T. Instead T I want the to be a concrete Class (Like Integer or MyCLass). Basically I need a generic List Type, but concrete at the point of execution. Is there a way to acomplish that?
-----Edit 1-----
It is not a duplicate of this question: https://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime
The answer there produces the same result as my code does.
答案1
得分: 2
由于类型擦除,在getListClass
内部无法在运行时获得T
参数,但您可以使用TypeToken.where
(来自Guava)通过cls
构建类型:
public <T> Type getListClass(Class<T> cls) {
Type type = new TypeToken<ArrayList<T>>() {}.where(new TypeParameter<T>() {}, cls).getType();
return type;
}
英文:
Due to type erasure, the T
parameter isn't available at runtime inside getListClass
, but you can use TypeToken.where
(from Guava) to build the type using cls
:
public <T> Type getListClass(Class<T> cls) {
Type type = new TypeToken<ArrayList<T>>() {}.where(new TypeParameter<T>() {}, cls).getType();
return type;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论