有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java编译错误是因为类型检查还是三元运算符?

最近,我在下面的代码中遇到了一个编译错误:

import org.eclipse.swt.widgets.TreeItem;
Object parent; // can only be a Tree or a TreeItem    
...
TreeItem item = new TreeItem((parent instanceof TreeItem) ? (TreeItem) parent : (Tree) parent, SWT.NONE);

编译器说:“构造函数TreeItem(Widget,int)未定义”

然后我尝试了另一个代码:

Object x = new Integer(1);

Test t = new Test((x instanceof String) ? (String) x : (Integer) x);

class Test{
    public Test(String s){}
    public Test(Integer i){}
}

还有一个错误:“构造函数测试(Object&;Serializable&;Comparable)未定义”

所以我不得不使用传统的if-else结构。你知道为什么编译器会这样吗


共 (2) 个答案

  1. # 1 楼答案

    好像我们在谈论这门课。请注意,构造函数接受TreeTreeItem

    现在,您正试图使用instanceofObject转换为正确的类型。到目前为止还不错(不过设计有点争议)。不幸的是,三元运算符表达式类型必须在编译时解析。与此方法相比,TreeItemTree最具体的公共超类是Widget

    public Widget smartCast(Object parent) {
        if(parent instanceof TreeItem) {
            return (TreeItem)parent;
        } else {
            return (Tree)parent;
        }
    }
    

    smartCast不能有Widget以外的任何其他返回类型,就像三元运算符一样

  2. # 2 楼答案

    JLS §15.25描述了三元运算符

    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) (§15.12.2.7).

    基本上,您可以将三元运算符视为一种方法:它只能有一个“返回类型”。由于StringInteger是两个不同的对象,它会找到共同的超类和由它们实现的所有接口,并从中创建一个返回类型。(StringInteger都实现了SerializableComparable并扩展了Object,所以你得到了Object & Serializable & Comparable。)