Java 泛型方法语法<;类型>;方法()
我刚刚发现在Java中可以实现以下功能: 我们有一个方法:Java 泛型方法语法<;类型>;方法(),java,generics,Java,Generics,我刚刚发现在Java中可以实现以下功能: 我们有一个方法: public <T> void doSomething( T value ); 或者我们可以用我刚刚发现的方式来称呼它: // Restricts the argument type to String this.<String>doSomething( "Hello World" ); 问题: 为什么我应该在哪里使用this.method(…)语法而不是通常的this.method(…)语法 是否存在差
public <T> void doSomething( T value );
或者我们可以用我刚刚发现的方式来称呼它:
// Restricts the argument type to String
this.<String>doSomething( "Hello World" );
问题:
- 为什么我应该在哪里使用
语法而不是通常的this.method(…)
语法this.method(…)
- 是否存在差异(参数的compiletime类型限制除外)
this.method(…)
语法
通常的this.method(…)
语法是什么
当需要显式提供类型参数时,可以使用前者。如果不这样做,将为您推断一个类型,但它可能不是您想要的
为什么以及在哪里使用this.method(…)
语法
通常的this.method(…)
语法是什么
当需要显式提供类型参数时,可以使用前者。如果不这样做,将为您推断类型,但它可能不是您想要的。当由于某种原因无法自动推断类型时,语法非常方便。 有很多这样的情况。例如,如果返回值派生自泛型类型,并且它是更复杂表达式的一部分,则该类型不明显 例如:
<T> T someMethod(T o) {
return o;
}
Number res = (num == null) ? this.<Number>someMethod(null) : null;
T方法(to){
返回o;
}
数字res=(num==null)?this.someMethod(null):null;
如果没有特殊语法(无法编译),此示例将无法工作,因为无法在此表达式中推断类型
还请注意,可以使用类似的语法来调用静态方法。例如,以下代码段导致编译错误:
Collection<Integer> getCollection() {
return someCondition ? Collections.emptyList() : Collections.singletonList(Integer.valueOf(42));
}
Collection getCollection(){
return someCondition?Collections.emptyList():Collections.singletonList(Integer.valueOf(42));
}
因此,我们必须指定类型:
Collection<Integer> getCollection() {
return someCondition ? Collections.<Integer>emptyList() : Collections.singletonList(Integer.valueOf(42));
}
Collection getCollection(){
return someCondition?Collections.emptyList():Collections.singletonList(Integer.valueOf(42));
}
至于你的第二个问题:除了明确给出泛型类型之外,没有其他区别。当由于某种原因无法自动推断类型时,语法非常方便。 有很多这样的情况。例如,如果返回值派生自泛型类型,并且它是更复杂表达式的一部分,则该类型不明显 例如:
<T> T someMethod(T o) {
return o;
}
Number res = (num == null) ? this.<Number>someMethod(null) : null;
T方法(to){
返回o;
}
数字res=(num==null)?this.someMethod(null):null;
如果没有特殊语法(无法编译),此示例将无法工作,因为无法在此表达式中推断类型
还请注意,可以使用类似的语法来调用静态方法。例如,以下代码段导致编译错误:
Collection<Integer> getCollection() {
return someCondition ? Collections.emptyList() : Collections.singletonList(Integer.valueOf(42));
}
Collection getCollection(){
return someCondition?Collections.emptyList():Collections.singletonList(Integer.valueOf(42));
}
因此,我们必须指定类型:
Collection<Integer> getCollection() {
return someCondition ? Collections.<Integer>emptyList() : Collections.singletonList(Integer.valueOf(42));
}
Collection getCollection(){
return someCondition?Collections.emptyList():Collections.singletonList(Integer.valueOf(42));
}
至于你的第二个问题:除了明确给出泛型类型之外,没有其他区别。我无法想象推断出的类型是错误的。@bastifunk Java 8中有改进,但是请看一个例子。我无法想象一个例子中推断出的类型是错误的。@bastifunk Java 8中有一些改进,但请看一个例子。