gpt4 book ai didi

java - 为什么三元运算符不能在 java 中的方法参数中工作

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:45 24 4
gpt4 key购买 nike

我在开发过程中注意到了这一点。

为什么三元运算符在方法参数中不起作用?这里显然是 InputStream 或 (else) String

class A{

public static boolean opAlpha(InputStream inputStream) {

// Do something

return true;

}

public static boolean opAlpha(String arg) {

// Do something else

return true;
}

public static void main(String[] args) throws Exception {

boolean useIsr = true;

InputStream inputStream = null;
String arg = null;

// boolean isTrue = useIsr ? A.opAlpha(inputStream): A.opAlpha(arg); // This is OK.
boolean isTrue = A.opAlpha(useIsr ? inputStream : arg); // This is not. (Error : The method opAlpha(InputStream) in the type A is not applicable for the arguments (Object))

}

}

最佳答案

编译器需要决定它应该在您的main 方法中调用哪个重载方法。方法调用必须放在 main 的编译字节码中,而不是在运行时决定。

事实上,即使知道条件表达式的类型是InputStreamString,编译器仍将其类型视为对象。来自 Section 15.25.3 of the Java Language Specification :

A reference conditional expression is a poly expression if it appears in an assignment context or an invocation context (§5.2. §5.3). Otherwise, it is a standalone expression.

Where a poly reference conditional expression appears in a context of a particular kind with target type T, its second and third operand expressions similarly appear in a context of the same kind with target type T.

The type of a poly reference conditional expression is the same as its target type.

The type of a standalone reference conditional expression is determined as follows:

  • If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.

  • If the type of one of the second and third operands is the null type, and the type of the other operand is a reference type, then the type of the conditional expression is that reference type.

  • Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2).

其中 lub(T1, T2) 代表 "Least Upper Bound" T1T2 类型。 InputStreamString的最小上界类型是Object

关于java - 为什么三元运算符不能在 java 中的方法参数中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30953259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com