0

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

组合框填充了一组制造商对象(它们实现了 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 新手,但我相当确定我对组合框所做的并不是最佳实践,但因为它适用于一个有具体截止日期的大学项目,而且它似乎对出于这个目的,我宁愿离开讨论填充组合框以解决另一个问题的更好方法。

4

4 回答 4

1

Yes, it is required. This makes it easier for the programmers who had to implement the java compiler. If this feature was to be implemented, they would have to go through a large amount of agony, writing code to find out if a particular object was guaranteed to be a particular type through if statements, which nobody would ever want to do, and the java compiler would remain perfectly functional without it. Plus, probably nobody thought of it.

So, sorry, there is no sane way to do this without a cast.

于 2013-08-24T23:31:21.823 回答
1

您仍然必须强制转换实例,但是使用instanceoffirst 进行测试意味着编译器不会引发未经检查的强制转换警告,并且还意味着您在运行时不会对java.lang.ClassCastException如果对象结果是您没想到的东西感到惊讶。

于 2013-08-24T23:31:10.620 回答
0

If it is not an instance of String, it will not go to the if block only. So you don't need to cast in if part of your code.

于 2013-08-24T23:30:43.043 回答
0

instanceof如果您使用的是 java 7,我认为有一个没有和 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()不打算这样使用,在国际化的情况下会出现问题),您可以提供ListCellRenderer代替,如问题JComboBox 设置标签和值

于 2013-08-24T23:59:05.167 回答