简体   繁体   中英

Generic method syntax <Type>method()

I just discovered that the following is possible in 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:

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?
  • 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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