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

Why is the Ternary operator not working inside a method argument in java

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

为什么三元运算符在方法参数中不起作用?这里明明是InputStream or (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,编译器认为它的类型是Object。来自 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" 类型 T1T2InputStreamString的最小上限类型是Object.

表达式 useIsr ? inputStream : arg 的类型是 Object,因为这是 inputStream (InputStream) 和 arg (String).

您没有任何接受 ObjectopAlpha 方法。因此编译错误。