作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个具有一些相同方法的类,下面的方法应该根据选中的复选框来访问两个类之一的方法,但是我在将 IF 语句中创建的对象传递到主体时遇到问题该方法的。有没有办法在不将方法主体复制到这两个区域的情况下实现这一目标?这是代码:
public void populateSupplyChainTextFields() {
if (jDeliveryCheckBox.isSelected() == true) {
DeliveryCompany supplyChainMember = new DeliveryCompany();
supplyChainMember = theDeliveryCompanyList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
} else {
Supplier supplyChainMember = new Supplier();
supplyChainMember = theSupplierList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
}
jCategoryTextField.setText(supplyChainMember.getCategory());
jPriceTextField.setText(String.valueOf(supplyChainMember.getPrice()));
jUnitCostTextField.setText(String.valueOf(supplyChainMember.getUnitCost()));
编辑**
为了确认,getBusinessName() 方法同时存在于 seller 类和deliveryCompany 类中。
如果这是一个新手问题,我很抱歉,我对 Java 还很陌生,任何有关这方面的帮助都是值得赞赏的。
最佳答案
正如许多人在这里提到的,最好的办法是让 Supplier
和 DeliveryCompany
实现注释接口(interface)或扩展公共(public)基类。
如果您确实无法做到这一点,并且确实必须避免 block 中的重复,并且实际上如果您的实际代码比您发布的代码更复杂,您可以使您的 block 共享一个变量
使用本地类来保存数据
public void populateSupplyChainTextFields() {
class Holder {
String category, price, unitCost;
Holder(String category, double price, double unitCost){
this.category = category;
this.price = String.valueOf(price);
this.unitCost = String.valueOf(unitCost);
}
}
Holder data;
if (jDeliveryCheckBox.isSelected()) {
DeliveryCompany supplyChainMember = new DeliveryCompany().Find(jSupplyChainSearchBox.getSelectedItem().toString());
data = new Holder(supplyChainMember.getCategory(), supplyChainMember.getPrice(), supplyChainMember.getUnitCost());
} else {
Supplier supplyChainMember = new Supplier().Find(jSupplyChainSearchBox.getSelectedItem().toString());
data = new Holder(supplyChainMember.getCategory(), supplyChainMember.getPrice(), supplyChainMember.getUnitCost());
}
jCategoryTextField.setText(data.category);
jPriceTextField.setText(data.price);
jUnitCostTextField.setText(data.unitCost);
使用本地类只是我的偏好,您可以选择使用诸如 map 之类的东西(当然引入后记录会非常方便):
Map<String, String> data;
if (jDeliveryCheckBox.isSelected()) {
DeliveryCompany supplyChainMember = ...
data = Map.of("category, supplyChainMember.getCategory(),
"price", String.valueOf(supplyChainMember.getPrice()),
"unitCost", String.valueOf(supplyChainMember.getUnitCost()));
} else {
Supplier supplyChainMember = ...
data = Map.of("category, supplyChainMember.getCategory(),
"price", String.valueOf(supplyChainMember.getPrice()),
"unitCost", String.valueOf(supplyChainMember.getUnitCost()));
}
jCategoryTextField.setText(data.get("category"));
jPriceTextField.setText(data.get("price"));
jUnitCostTextField.setText(data.get("unitCost"));
关于java - 有没有办法创建一个对象,其中对象类由另一个变量定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59797191/
我是一名优秀的程序员,十分优秀!