在Java中,假设我们有一个带参数double a
的函数。如果我传递一个整数作为参数,它是否有效? (我的意思是,是否存在隐式转换?)在相反的情况下:如果我有例如一个整数作为参数,我传递一个双?
不幸的是,我目前无法编译我的代码,我想查看这个断言。 谢谢你的关注。
答案 0 :(得分:12)
有关Method Invocation Conversion
的详细信息,请参阅JLS - Section # 5.3。
方法调用上下文允许使用以下之一:
- an identity conversion (§5.1.1) - a widening primitive conversion (§5.1.2) - a widening reference conversion (§5.1.5) - a boxing conversion (§5.1.7) optionally followed by widening reference conversion - an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
因此,根据规则#2 ,您的第一次调用(int
到double
)将正常工作。
但根据同一部分中引用的声明,第二次调用(double
到int
)将给出编译器错误: -
如果表达式的类型无法转换为类型 参数通过方法调用上下文中允许的转换, 然后发生编译时错误。
答案 1 :(得分:3)
因为您可以将double设置为整数,所以使用integer作为参数可以使用double作为参数。其他方式失败。在这种情况下,您需要将double转换为int。同样适用于正常的受让人,例如..
int i = 6;
double d = 0;
d = i; /* ok
i = d ; /* not ok
答案 2 :(得分:1)
你可以通过让你的函数取Number
的参数来解决这个问题。这是Integer
和Double
都继承的对象,所以直到Double
数字和Integer
数字的行为相同,这才有效。
请注意,基元integer
和double
以及对象Integer
和Double
之间存在差异。 Java使用自动装箱在函数调用等中自动转换这些类型。
答案 3 :(得分:0)
最初,原始扩展会针对原始类型发生。 例如您要致电
int input = 5; //int variable;
apply(input); //calling method with int value.
但是您的类没有包含参数接受 int 的方法,因此编译器将进行原始扩展。它将检查是否存在 java long 参数的任何 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.
}
接下来,如果未找到以上所有三种方法,则编译器将查找自动装箱,然后尝试将其转换为相应的包装器。为 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);
然后,编译器将尝试通过精确类型或原始加宽或自动装箱或数组匹配的方式找到匹配项。