Java中的通用方法参数的getClass() [英] getClass() of a Generic Method Parameter in a Java
问题描述
以下Java方法无法编译:
The following Java method fails to compile:
<T extends Number> void foo(T t)
{
Class<? extends T> klass = t.getClass();
}
收到的错误是:
类型不匹配:无法转换为 Class< capture#3-of?将Number>
扩展为 Class<?扩展T>
Error received is:
Type mismatch: cannot convert from Class<capture#3-of ? extends Number>
to Class<? extends T>
有人可以解释为什么 Class<?扩展T>
无效,但 Class<? extends Number>
没问题?
Can someone explain why Class<? extends T>
is invalid, but Class<? extends Number>
is fine?
Javadoc 说:
实际结果类型是
类< ;? extends | X |>
其中| X |是擦除调用getClass的表达式的静态类型。例如,此代码片段中不需要强制转换:
The actual result type is
Class<? extends |X|>
where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:
Number n = 0;
Class<? extends Number> c = n.getClass();
推荐答案
因为 T
class'type不从 T
延伸。相反,它从 Number
延伸,正如您在< T extends Number>
中声明的那样。就那么简单。
Because the T
class' type doesn't extend from T
. Instead, it extends from Number
, exactly as you have declared yourself in <T extends Number>
. Simple as that.
更好的问题是:
为什么不进行以下编译?
Why doesn't the following compile?
<T extends Number> void foo(T t)
{
Class<T> class1 = t.getClass();
}
答案就是 Object#getClass()
返回 Class<?>
带有无界通配符?
因为对象本身并不直接了解其在任意方法中所期望的泛型类型。
The answer to that is that the Object#getClass()
returns Class<?>
with an unbounded wildcard ?
because the object itself is not directly aware about its generic type which is been expected in an arbitrary method.
这篇关于Java中的通用方法参数的getClass()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!