【问题标题】:Casting known object types转换已知对象类型
【发布时间】:2013-08-27 18:21:30
【问题描述】:

我正在开发一个项目,让您可以在数据库中创建产品。它包括一个带有可编辑组合框的表单,因此您可以为新产品选择预先存在的制造商,或者输入您想要与产品一起创建的新制造商的名称。

组合框填充了一组制造商对象(它们实现了 toString(),因此它们显示了一些有意义的东西)。

目前处理组合框输出的逻辑是这样实现的:

Object mfr = mfctrCombo.getSelectedItem ();
Product newPrd = new Product ();

// If the mfr is a string then we need to create a new Manufacturer
if (mfr instanceof String) {
    Manufacturer newMfr = new Manufacturer ();
    newMfr.setName ((String) mfr);
    // Logic for persisting the new Manufacturer goes here
    newPrd.setManufacturer (newMfr);
} else if (mfr instanceof Manufacturer) {
    newPrd.setManufacturer ((Manufacturer) mfr);
}
// Logic for persisting the new Product goes here

这确实有效,但对我来说似乎不需要强制转换 mfr 对象。我在 if 块的开头进行 instanceof 检查,所以我知道对象在块内的类型是什么。在开始检查后是否真的有必要在块内进行强制转换?在我看来,它不应该是必需的。

虽然我是 Java 新手,但我相当确定我使用组合框所做的并不是最佳实践,但因为它适用于一个有具体截止日期的大学项目,而且它似乎有效为此目的,我宁愿离开讨论填充组合框以解决另一个问题的更好方法。

【问题讨论】:

    标签: java casting


    【解决方案1】:

    如果您使用的是 java 7,我认为没有 instanceof 和 cast 的解决方案:

    ComboBoxModel<Manufacturer> model = new DefaultComboBoxModel<>();
    // Initialize model with existing manufacturers model.addElement(...)
    JComboBox<Manufacturer> mfctrCombo = new JComboBox<>(model);
    
    // ...
    
    int selectedIndex = mfctrCombo.getSelectedIndex();
    Product newPrd = new Product ();
    
    if (selectedIndex == -1) {
        // The user provided a string then we need to create a new Manufacturer    
        Manufacturer newMfr = new Manufacturer ();
        newMfr.setName (mfctrCombo.getSelectedItem().toString());
        // Logic for persisting the new Manufacturer goes here
        newPrd.setManufacturer (newMfr);
    } else {
        ComboBoxModel<Manufacturer> model = mfctrCombo.getModel();
        newPrd.setManufacturer (model.getElementAt(selectedIndex);
    }
    

    此外,您不需要依赖toString() 在 GUI 上显示文本(toString() 并不是要那样使用,在国际化的情况下会出现问题),您可以提供一个 @987654321 @ 代替,如问题JComboBox setting label and value 所示。

    【讨论】:

      【解决方案2】:

      您仍然必须强制转换实例,但是首先使用instanceof 进行测试意味着编译器不会发出未经检查的强制转换警告,并且还意味着如果对象结果在运行时出现java.lang.ClassCastException,您也不会感到惊讶出乎你的意料。

      【讨论】:

        【解决方案3】:

        是的,这是必需的。这使得必须实现 java 编译器的程序员更容易。如果要实现此功能,他们将不得不经历大量的痛苦,编写代码以通过 if 语句来确定特定对象是否是特定类型,这是没人愿意做的,并且没有它,java 编译器将保持完美的功能。另外,可能没人想到。

        所以,抱歉,没有演员表就没有理智的方法。

        【讨论】:

          【解决方案4】:

          如果它不是 String 的实例,它不会只转到 if 块。 所以你不需要在你的代码中加入 if 部分。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多