将带有参数的类传递到 Class<T> 中。

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

Pass class with parameter into Class<T>

问题

有没有办法我们可以将带有参数的类类型传递给一个接受 Class<T> 的方法?

假设我有这个方法:

public <T> T getProperty(Class<T> type)

给定这个方法 getProperty,它会返回我们传递的任何类型。有没有办法我可以传递类似于 Map 并带有参数的类呢?就像这样:

getProperty(Map<String, String>.class)

不幸的是,上面的代码片段会给我编译错误。使用 Map.class 是可以的,但我想消除泛型警告并且拥有强类型的参数。

英文:

Is there a way we can pass class type with parameter into a method that accepts Class&lt;T&gt;?

Let's say I have this method:

>public <T> T getProperty(Class<T> type)

Given the method, getProperty, which returns whatever type we passed, is there a way I can pass class like Map with parameter? Lets say like this:

> getProperty(Map<String, String>.class)

Unfortunately, the code snippet above is giving me compilation error. Using Map.class will work though but I would like to eliminate the generic warning and have a strong-typed argument.

答案1

得分: 2

实际上,使用强类型参数是没有意义的。因为 Java 会在运行时擦除类型参数。所有类型的 Map 都引用相同的类对象。

即使你可以这样做,对于 getProperty(Class type) 方法来说,传递 Map.class 还是 Map<String, String>.class 没有任何区别。因此,它能做的最好的事情就是返回原始类型。

英文:

In fact use strong-typed argument is meaningless. Because java will erase the type parameter at runtime. All kinds of Map refer to the same Class Object.

Even if you can,it make no difference for getProperty(Class type) method whether you pass Map.class or Map&lt;String,String&gt;.class. So the best thing it can do is return a raw type.

huangapple
  • 本文由 发表于 2020年9月22日 10:52:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64002421.html
匿名

发表评论

匿名网友

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

确定