方法调用如何进行类型推断? [英] How type inference work for method calls?

查看:52
本文介绍了方法调用如何进行类型推断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

public class Learn {
    public static <T> T test (T a, T b) {
        System.out.println(a.getClass().getSimpleName());
        System.out.println(b.getClass().getSimpleName());
        b = a;
        return a;
    }

    public static void main (String[] args) {
        test("", new ArrayList<Integer>());
    }
}

main方法中,我使用StringArrayList <Integer>对象调用test.两者都是不同的东西,通常将ArrayList分配给String会产生编译错误.

In the main method, I am calling test with a String and an ArrayList <Integer> object. Both are different things and assigning an ArrayList to String (generally) gives a compile error.

String aString = new ArrayList <Integer> (); // won't compile

但是我正是在test的第三行中这样做,程序可以编译并运行良好.首先,我认为类型参数T被替换为同时与StringArrayList兼容的类型(如Serializable).但是test中的两个println语句分别将"String"和"ArrayList"打印为ab的类型.我的问题是,如果在运行时aStringbArrayList,我们如何将a分配给b.

But I am doing exactly that in the 3rd line of test and the program compiles and runs fine. First I thought that the type parameter T is replaced by a type that's compatible with both String and ArrayList (like Serializable). But the two println statements inside test print "String" and "ArrayList" as types of a and b respectively. My question is, if ais String and b is ArrayList at runtime, how can we assign a to b.

推荐答案

对于通用方法,Java编译器将

For a generic method, the Java compiler will infer the most specific common type for both parameters a and b.

推理算法确定参数的类型,以及确定结果是否被分配或返回的类型(如果可用).最后,推理算法会尝试找到最适合所有参数的特定类型.

您没有将对test的调用结果分配给任何对象,因此没有目标可以影响推断.

You aren't assigning the result of the call to test to anything, so there is no target to influence the inference.

在这种情况下,即使StringArrayList<Integer>都有一个通用的超类型Serializable,所以T被推断为Serializable,并且您始终可以将一个相同类型的变量分配给另一个.对于其他示例,您甚至可能会找到Object作为常见超类型.

In this case, even String and ArrayList<Integer> have a common supertype, Serializable, so T is inferred as Serializable, and you can always assign one variable of the same type to another. For other examples, you may even find Object as the common supertype.

但是仅仅因为您有类型为T的变量被推断为Serializable,所以对象本身仍然是StringArrayList,因此获取其类并打印其名称仍会打印StringArrayList.您不是在打印变量的类型;而是在打印变量的类型.您正在打印对象的类型.

But just because you have variables of type T that are inferred as Serializable, the objects themselves are still a String and an ArrayList, so getting their classes and printing their names still prints String and ArrayList. You're not printing the type of the variables; you're printing the type of the objects.

这篇关于方法调用如何进行类型推断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆