gpt4 book ai didi

java - 泛型方法调用

转载 作者:行者123 更新时间:2023-12-03 23:06:12 26 4
gpt4 key购买 nike

如果我们有泛型方法

class SClass{
public static <T> ArrayList<T> listFactory(){ return new ArrayList<T>(); }
}

我们可以定义类型参数T调用此方法时显式。

SClass.<?>listFactory();//compile error
SClass.<List<?>>listFactory();//ok

为什么我们不能调用 listFactory带有类型参数 ? , 但可以用 List<?>

最佳答案

rules of method invocation are described in the Java Language Specification .在这种情况下,我们感兴趣的是

A method invocation expression is used to invoke a class or instancemethod.

[...]
TypeName . NonWildTypeArguments Identifier ( ArgumentListopt )

<?>是野生型,<List<?>>不是。

至于为什么,考虑一下

SClass.<?>listFactory();//compile error

你甚至可以用 <?> 做什么?在listFactory()?未知。你做不到

new ArrayList<?>(); 

因为 JLS prohibits it

It is a compile-time error if any of the type arguments used in aclass instance creation expression are wildcard type arguments(§4.5.1).

但你也不能将它与其他任何东西一起使用。

关于java - 泛型方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19716161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com