Possible Duplicate:
Determining the Type for a generic method parameter at runtime
Generics in static methods
The code below fails at runtime with cannot select from a type variable. Is there any way of doing this without having to pass the type as a parameter (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("");
}
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)
With Generics you have the added bonus of type erasure. This mean
E[]is actuallyDeal[]at runtime. Which Deal type you might have liked is lost.