用于在方法调用中显式指定泛型参数的 Java 语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3012781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java-syntax for explicitly specifying generic arguments in method calls
提问by Hans-Peter St?rr
What is the syntax for explicitly giving the type parameters for a generic Java method?
为泛型 Java 方法显式提供类型参数的语法是什么?
采纳答案by Theodore Norvell
The following is notthe syntax
以下不是语法
<ArgType>genericMethod()
It seems the type arguments mustcome after a dot as in
似乎类型参数必须跟在一个点之后,如
SomeClass.<ArgType>genericMethod()
this.<ArgType>genericMethod()
p.<ArgType>genericMethod()
super.<ArgType>genericMethod()
SomeClass.super.<ArgType>genericMethod()
SomeClass.this.<ArgType>genericMethod()
回答by Hans-Peter St?rr
According to the Java specificationthat would be for example:
根据Java 规范,例如:
Collections.<String>unmodifiableSet()
(Sorry for asking and answering my own question - I was just looking this up for the third time. :-)
(对不起,我问并回答了我自己的问题——我只是第三次查这个。:-)
回答by krock
A good example from java.util.Collectionof specifying a generic method which defines its own generic type is Collection.toArraywhere the method signature looks like:
java.util.Collection指定定义其自己的泛型类型的泛型方法的一个很好的例子是Collection.toArray方法签名如下所示:
<T> T[] toArray(T[] a);
This declares a generic type T, which is defined on method call by the parameter T[] aand returns an array of T's. So the same instance could call the toArray method in a generic fashion:
这声明了一个泛型类型 T,它是在方法调用时由参数定义的,T[] a并返回一个 T 的数组。因此,同一个实例可以以通用方式调用 toArray 方法:
Collection<Integer> collection = new ArrayList<Integer>();
collection.add(1);
collection.add(2);
// Call generic method returning Integer[]
Integer[] ints = collection.toArray(new Integer[]{});
// Call generic method again, this time returning an Number[] (Integer extends Number)
Number[] nums = collection.toArray(new Number[]{});
Also, see the java tutorial on generic type parameters.

