Java泛型 - 为什么“不兼容的类型”如果在调用的方法中不存在类的泛型类型,则编译错误? [英] Java generics - Why "incompatible types" compilation error if a class' generic type doesn't exist in an invoked method?
问题描述
请注意下面的代码无法编译,方法结果分配失败: String s = a.method(abc);
。
Please notice the code below doesn't compile, failing on the method result assignment: String s = a.method("abc");
.
编译错误:不兼容的类型:java.lang.Object无法转换为java.lang.String
但是,当将 A a
更改为 A<?>时a
或 A< Object> a
,编译通过。
But, when changing A a
to A<?> a
or to A<Object> a
, the compilation passes.
*请注意类型< T>
该方法中的类型与类中的类型< O>
不同。
* Please notice that the type <T>
in the method is different than the type <O>
in the class.
任何想法编译的内容错误?另外,为什么变量 a
中的泛型定义解决了编译问题?
Any idea what the compilation error? Also, why the generic definition in variable a
solves the compilation issue?
class A<O>
{
O something;
<T> T method(T t)
{
return t;
}
static void testJavaStrangeGenericDefinitionBehavior()
{
A a = null;
String s = a.method("abc");
}
}
推荐答案
A a = null;
应为:
A<String> a = null; // or better yet, new A<String>();
虽然,你可以用任何类代替 String
因为,正如你所说, T
和 O
泛型是不同的类型。
Although, you could substitute any class for String
since, as you say, the T
and O
generics are different types.
删除泛型参数后,您将丢失方法调用中的所有泛型,这基本上等同于调用:
Once you remove the generic parameter, you lose all the generics in your method call, which essentially becomes equivalent to calling:
Object method(Object t);
这篇关于Java泛型 - 为什么“不兼容的类型”如果在调用的方法中不存在类的泛型类型,则编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!