Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a Java method with an explicit type parameter without specifying the class?

Tags:

java

generics

The following code does not compile, because Java cannot infer the type parameter to getSomething:

class Example {
  static void callIt() {
    takeString(getSomething());
  }

  static void takeString(String s) {
  }

  static <T> T getSomething() {
    return null;
  }
}

Is there some way to specify the type parameter like <String>getSomething(), but without specifying the name of the class it is being called on? i.e. not Example.<String>getSomething().

like image 478
Andrew Walbran Avatar asked Dec 01 '25 08:12

Andrew Walbran


1 Answers

Is there some way to specify the type parameter like <String>getSomething(), but without specifying the name of the class it is being called on? i.e. not Example.<String>getSomething()

No, there is not. That is the syntax for explicitly providing a type argument to a generic method.

Your code should compile on Java 8, with its improved and targeted type inference.

like image 177
Sotirios Delimanolis Avatar answered Dec 03 '25 22:12

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!