0

可能重复:
在运行时确定泛型方法参数的类型
静态方法中的泛型

下面的代码在运行时失败,并带有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("");
}
4

1 回答 1

2

A problem is that the right hand size of = has no idea what type you want on the left hand side. i.e. java doesn't do this kind of type inference.

A method doesn't know what type you need a return type to be. (I have seen exceptions at runtime with MethodHandles and I suspect that Java 8 or 9 might introduce these features)

e.g. very basic type inference for return types isn't done at runtime (or compile time)

public Double getValue() {
    return 5.0;
}

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

With Generics you have the added bonus of type erasure. This mean E[] is actually Deal[] at runtime. Which Deal type you might have liked is lost.

于 2012-08-31T11:38:38.887 回答