Return getClass 方法的类型
Return type of getClass method
Object
中方法 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.
那么为什么 foo
可以编译而不是 bar
?
static void foo(String s) {
try {
Class<? extends String> clazz = s.getClass();
} catch (Exception e) {
}
}
static <T> void bar(T t) {
try {
Class<? extends T> clazz = t.getClass();
} catch (Exception e) {
}
}
编辑
我接受了 yshavit 的回答,因为它清楚地回答了我的问题,但我仍然很想知道他们为什么这样定义它。他们可以将其定义为 Class<? extends T>
类型,其中 T
是表达式的静态类型。我不清楚为什么有必要在这个阶段擦除类型信息。如果类型是 List<String>
就有意义,但如果是 T
就不是。我会对任何解释这一点的答案投赞成票。
Object
中方法 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.
那么为什么 foo
可以编译而不是 bar
?
static void foo(String s) {
try {
Class<? extends String> clazz = s.getClass();
} catch (Exception e) {
}
}
static <T> void bar(T t) {
try {
Class<? extends T> clazz = t.getClass();
} catch (Exception e) {
}
}
编辑
我接受了 yshavit 的回答,因为它清楚地回答了我的问题,但我仍然很想知道他们为什么这样定义它。他们可以将其定义为 Class<? extends T>
类型,其中 T
是表达式的静态类型。我不清楚为什么有必要在这个阶段擦除类型信息。如果类型是 List<String>
就有意义,但如果是 T
就不是。我会对任何解释这一点的答案投赞成票。