简体   繁体   English

通用方法语法 <Type> 方法()

[英]Generic method syntax <Type>method()

I just discovered that the following is possible in Java: 我刚刚发现在Java中可以实现以下功能:

We have a method: 我们有一个方法:

public <T> void doSomething( T value );

And we can call it like this: 我们可以这样称呼它:

this.doSomething( "Hello World" );

Or we can call it the way I just found out: 或者我们可以用我刚刚发现的方式来称呼它:

// Restricts the argument type to String
this.<String>doSomething( "Hello World" ); 

At first I thought this could be quite handy if we have to do with class comparison because we know the type of T at compile time, but the generics aren't a runtime feature so this won't work: 起初,我认为如果必须进行类比较,这会非常方便,因为我们在编译时就知道T的类型,但是泛型不是运行时功能,因此无法使用:

public <T> void doSomething( T value ) {
    if ( field instanceof T ) ...  // Not working
}

Questions: 问题:

  • Why and where should I use the this.<Type>method( ... ) syntax over the usual this.method( ... ) syntax? 为什么和在通常的this.method( ... )语法上使用this.<Type>method( ... ) this.method( ... )语法?
  • Are there differences (except for the compiletime type restriction for the argument)? 是否有区别(参数的编译时类型限制除外)?

The syntax is handy when the type cannot be inferred automatically for some reason. 当由于某种原因无法自动推断类型时,该语法非常方便。 There are many situations like that. 有很多类似的情况。 For instance, if the return value is derived from the generic type and it is part of a more complex expression, so the type is not apparent. 例如,如果返回值是从泛型类型派生的,并且它是更复杂的表达式的一部分,则该类型不明显。

Example: 例:

<T> T someMethod(T o) {
    return o;
}

Number res = (num == null) ? this.<Number>someMethod(null) : null;

This example would not work without the special syntax (could not be compiled), because the type cannot be inferred inside this expression. 如果没有特殊语法(无法编译),此示例将无法工作,因为无法在此表达式中推断类型。

Also note that a similar syntax may be used to call a static method. 还要注意,可以使用类似的语法来调用静态方法。 For example the following snippet results in a compile error: 例如,以下代码片段导致编译错误:

Collection<Integer> getCollection() {
    return someCondition ? Collections.emptyList() : Collections.singletonList(Integer.valueOf(42));
}

So we must instead specify the type: 因此,我们必须改为指定类型:

Collection<Integer> getCollection() {
    return someCondition ? Collections.<Integer>emptyList() : Collections.singletonList(Integer.valueOf(42));
}

As to your second question: There is no other difference beside the generic type being explicitely given. 关于您的第二个问题:除了明确给出的泛型类型之外,没有其他区别。

Why and where should I use the this.<Type>method( ... ) syntax over the usual this.method( ... ) syntax? 为什么和在通常的this.method( ... )语法上使用this.<Type>method( ... ) this.method( ... )语法?

You would use the former when you need to explicitly provide a type argument. 当您需要显式提供类型参数时,可以使用前者。 If you don't, a type will be inferred for you, but it might not be what you wanted. 如果您不这样做,则会为您推断类型,但这可能不是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM