gpt4 book ai didi

java - Java 中的泛型类型推断

转载 作者:行者123 更新时间:2023-12-02 07:36:04 26 4
gpt4 key购买 nike

Possible Duplicate:
Determining the Type for a generic method parameter at runtime
Generics in static methods

下面的代码在运行时失败,并显示 cannot select from a type variable 。有没有什么方法可以做到这一点而不必将类型作为参数传递( Class<E[]> type )?

public static <E extends Deal> E[] parseDealsFromJSON(String body) {
parser.fromJson(body, E[].class); // fails here
}

public static void main(String[] args) {
SubDeal[] deals = parseDealsFromJSON("");
}

最佳答案

一个问题是=的右手尺寸不知道你想要在左手边什么类型。即java不进行这种类型推断。

方法不知道您需要什么类型的返回类型。 (我在 MethodHandles 的运行时看到过异常,我怀疑 Java 8 或 9 可能会引入这些功能)

例如返回类型的非常基本的类型推断不是在运行时(或编译时)完成的

public Double getValue() {
return 5.0;
}

double d = m.getValue(); // not smart enough to avoid creating a `Double` here.
<小时/>

使用泛型,您可以获得类型删除的额外好处。这意味着 E[] 在运行时实际上是 Deal[]。您可能喜欢的交易类型已丢失。

关于java - Java 中的泛型类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12214405/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com