gpt4 book ai didi

java - 有没有办法创建一个对象,其中对象类由另一个变量定义?

转载 作者:行者123 更新时间:2023-12-01 18:47:39 24 4
gpt4 key购买 nike

我有两个具有一些相同方法的类,下面的方法应该根据选中的复选框来访问两个类之一的方法,但是我在将 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()));

编辑**

根据 Salim 的回复,这是我收到的错误消息: enter image description here

为了确认,getBusinessName() 方法同时存在于 seller 类和deliveryCompany 类中。

如果这是一个新手问题,我很抱歉,我对 Java 还很陌生,任何有关这方面的帮助都是值得赞赏的。

最佳答案

正如许多人在这里提到的,最好的办法是让 SupplierDeliveryCompany 实现注释接口(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com