当静态导入时,如何调用具有类型的通用方法?
我发现您可以使用特殊类型调用泛型方法,例如:
假设我们有一个泛型方法:
class ListUtils {
public static <T> List<T> createList() {
return new ArrayList<T>();
}
}
我们可以这样调用它:
List<Integer> intList = ListUtils.<Integer>createList();
但是当它静态导入时我们如何调用它?例如:
List<Integer> intList = <Integer>createList();
这不起作用。
I found that you can call a generic method with a special Type, e.g.:
suppose we have a generic method:
class ListUtils {
public static <T> List<T> createList() {
return new ArrayList<T>();
}
}
we can call it like:
List<Integer> intList = ListUtils.<Integer>createList();
But how can we call it when it's statically imported? e.g.:
List<Integer> intList = <Integer>createList();
this does not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你不能。您必须使用类名来引用它。
似乎具有:
并调用 foo(createList()) 并不能推断出正确的类型。因此,您应该显式使用类名称,例如
ListUtils.createList()
或使用中间变量:最后,guava 有
Lists.newArrayList()
,所以你最好重用它。You can't. You'd have to reference it using the class name.
It seems that having:
and calling
foo(createList())
does not infer the correct type. So you should either explicitly use the class name, likeListUtils.createList()
or use an intermediate variable:Finally, guava has
Lists.newArrayList()
, so you'd better reuse that.以下对我有用:
The following works for me:
你不能。这是Java语言语法的设计缺陷。 Scala 是 JVM 上较新的静态类型语言,它解决了这个问题。 (这是在 Scala 中进行调用的方式:
val intList: List[Int] = creatList[Int]()
)。You can't. This is a design flaw in the syntax of the Java language. Scala, which is a newer statically typed language on JVM, fixes this. (This is how you'd make that call in Scala:
val intList: List[Int] = creatList[Int]()
).我相信 Mindas 已经证明这应该与推理一起使用,你的语法有点偏离。不过我建议你看看 Google Guava,他们有这个确切的方法和其他几个有用的方法。没有意义重新发明轮子:)
I believe Mindas has already demonstrated that this should work with inference, your syntax is just a bit off. However I would recommend you have a look at Google Guava, they have this exact method and several other useful ones available. No sense re-inventing the wheel :)
据我所知,静态导入机制的一个缺点是,如果您希望提供形式参数,则必须指定调用对象/类。
Mindas 是正确的,当没有参数时,类型推断机制将使用函数返回值所分配的类型。然而,当你提供论点时,技巧就出现了。如果您希望避免指定调用对象/类,您可以通过参数的强制转换来键入提示,如下所示:
使用类型提示,类型推断将返回 Number 类型的对象,而不是 Integer 类型的对象,因为它会推理否则。
As far as I've read, a shortcoming of the static import mechanism is that you must specify the calling object/class if you wish to provide formal parameters.
Mindas is correct, when there are no arguments, the type inference mechanism will use the type that the function return value is being assigned to. The trick comes when you are providing arguments however. If you wish to avoid having to specify the calling object/class you can type hint through a cast of the arguments as such:
With the type hint, the type inference will return an object of type Number, instead of Integer as it would have reasoned otherwise.