本文介绍了通用类型解析 - 编译器步骤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设以下方法(Java 8): public< T>列表与LT;类< T>> getList(){
返回新的ArrayList<>();
}
public< T>列表与LT; T> getList2(){
返回新的ArrayList<>();
}
以下代码使用这些方法:
@Test
public void testLists(){
getList()。add(String.class); //不会编译
this。< String> getList()。add(String.class); //编译
getList2()。add(String.class); //编译
}
第二次和第三次调用编译正常, :
I do not fully understand the resolution steps here, maybe someone could explain why I need the type witness and the compiler does not infer the type automatically?
解决方案
Because the compiler doesn't/cannot infer generic arguments based on future method calls.
In your case, when you call getList()
or getList2()
the type T
is already inferred as Object
. This means getList()
will return you an List<Class<Object>>
object and you cannot add a Class<String>
object into it.
In your third statement, you have List<Object>
so you are able to add a Class<String>
to it.
这篇关于通用类型解析 - 编译器步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!