如何在不指定 class 的情况下使用显式类型参数调用 Java 方法?

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

以下代码无法编译,因为 Java 无法推断 getSomething 的类型参数:

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

  static void takeString(String s) {
  }

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

是否有某种方法可以像 <String>getSomething() 那样指定类型参数,但不指定调用它的 class 的名称?即不是 Example.<String>getSomething().

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()

不,没有。 That is the syntax for explicitly providing a type argument to a generic method.

您的代码应在 Java 8 上编译,具有改进和有针对性的类型推断。

你为什么不这样做:

static Object getSomething() {return null;}

然后将其转换为字符串:

takeString((String)getSomething());

从你的简短示例来看,不清楚你为什么需要泛型