以下代码在使用 -Xlint 编译时给出了两个警告。其中之一声明 typeC<Double>
是必需的,但C
已找到,即使返回类型非常清楚C<Double>
。
我找到了一个消除这两个警告的解决方案,但我不明白(也想知道)为什么这是一个警告以及为什么它消失了。
代码:
public class Test {
public static void main(String[] args) {
B b = new B();
thing(b);
}
static void thing(A a) {
C<Double> c = a.a();
}
}
abstract class A<T> {
C<Double> a() {
return new C<Double>();
}
}
class B extends A<String> {}
class C<T> {}
警告:
Test.java:7: warning: [rawtypes] found raw type: A
static void thing(A a) {
^
missing type arguments for generic class A<T>
where T is a type-variable:
T extends Object declared in class A
Test.java:8: warning: [unchecked] unchecked conversion
C<Double> c = a.a();
^
required: C<Double>
found: C
2 warnings
警告的解决方法:
我static void thing(A a)
改为static void thing(A<?> a)
.
但:
没有理由a.a()
返回C
,而不是C<Double>
随处说明的返回类型。当类型参数不影响时,我不明白为什么A
原始应该使其所有方法的返回类型都是原始的;A
.a()