问题
I am going through a tutorial and I found this particular code.
private <V> V fromJson(HttpRequest request, Class<V> target) throws IOException {
Reader reader = request.bufferedReader();
try {
return GSON.fromJson(reader, target);
} catch (JsonParseException e) {
throw new JsonException(e);
} finally {
try {
reader.close();
} catch (IOException ignored) {
// Ignored
}
}
}
I notice that the fromJson function has two return types? I have the basic idea of generics and how it works. What I can't understand is how are two types specified and how will this function know which type to assign the value to when its called.
回答1:
No, there is only one return type. The <V> declares the V generic type parameter (it makes the method generic), and the V after that is the actual return type.
Here's more information on generic methods in Java.
来源:https://stackoverflow.com/questions/17604970/what-does-it-mean-when-a-generics-function-has-two-return-types