最初原始扩展会发生在原始类型上。
比如你想调用
int input = 5; //int variable;
apply(input); //calling method with int value.
但是您的类不包含参数接受 int 的方法,因此编译器将使用 原始扩展。它将检查是否存在 java long 参数的任何 apply 方法。如果存在,将调用该方法。如果不是,它将检查 apply 是否存在 float 参数,然后将其选中。如果也没有找到它,它将寻找带有 double 参数的 apply。
public void apply(long input) {
System.out.println("long"); // first pick by the compiler.
}
public void apply(float input) {
System.out.println("float"); // if above method not found this will be selected.
}
public void apply(double input) {
System.out.println("double"); // above two methods not present this will be selected.
}
接下来,如果以上三个方法都没有找到,那么编译器将寻找 Autoboxing this 并尝试将其转换为相应的包装器。 int 是它的 java.lang.Integer。所以它会使用 Integer 参数检查 apply。如果这个找到的编译器会执行这个方法。
public void apply(Integer input) {
System.out.println("Integer");
}
最后,如果以上都不存在,编译器会查找名称为 apply 且接受 int... 或 Integer... 的任何方法> 并调用该方法。
public void apply(int... input) {
System.out.println("int...");
}
如果你的类只包含以下两种方法
public void apply(long input) {
System.out.println("long");
}
public void apply(float input) {
System.out.println("float");
}
如果你想向这个方法传递一个 double 值,它不会编译。
double input = 5d;
apply(input);
// The method apply(long) in the type YourClass
//is not applicable for the arguments (double
如果您想完成这项工作,您必须将其类型转换为您的方法可以接受的内容。
apply((int) input);
然后编译器将尝试通过精确类型或原始扩展或自动装箱或数组匹配方式找到匹配项。