如何在Java中使用类型变量创建带有参数的类型?

huangapple go评论66阅读模式
英文:

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 能够变成一个具体的类(比如 IntegerMyCLass)。基本上,我需要一个泛型的 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 &lt;T&gt; Type getListClass(Class&lt;T&gt; cls) {
    Type type = new TypeToken&lt;ArrayList&lt;T&gt;&gt;() {}.getType();
    return type;
}

Actual code:

如何在Java中使用类型变量创建带有参数的类型?

Debugger:

如何在Java中使用类型变量创建带有参数的类型?

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 &lt;T&gt; Type getListClass(Class&lt;T&gt; cls) {
    Type type = new TypeToken&lt;ArrayList&lt;T&gt;&gt;() {}.where(new TypeParameter&lt;T&gt;() {}, cls).getType();
    return type;
}

huangapple
  • 本文由 发表于 2020年10月21日 14:04:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64457544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定