本文介绍了当泛型函数具有两种返回类型时,这意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看一个教程,我找到了这个特殊的代码.

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
        }
    }
}

我注意到fromJson函数有两种返回类型吗?我对泛型及其工作原理有基本的了解.我无法理解的是如何指定两种类型,以及该函数如何在调用值时知道将值分配给哪种类型.

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.

推荐答案

不,只有一种返回类型. <V>声明V泛型类型参数(使该方法成为泛型),其后的V是实际的返回类型.

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.

这是有关Java泛型方法的更多信息.

这篇关于当泛型函数具有两种返回类型时,这意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:50