gpt4 book ai didi

Java getClass 返回不同的类

转载 作者:太空宇宙 更新时间:2023-11-04 14:15:34 27 4
gpt4 key购买 nike

我正在尝试创建其中包含文本字段的对话框。代码如下

private void showBatchDialog() {
Dialog<Batch> dialog = new Dialog<Batch>();
dialog.setTitle("Add batch");
dialog.setHeaderText("adding new batch");

ButtonType addButtonType = new ButtonType("Add batch",
ButtonData.OK_DONE);

Collection<ButtonType> buttons = new ArrayList<ButtonType>();
buttons.add(addButtonType);
buttons.add(ButtonType.CANCEL);

dialog.getDialogPane().getButtonTypes().addAll(buttons);

GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));

TextField code = new TextField();
code.setPromptText("code");
TextField name = new TextField();
name.setPromptText("name");
grid.add(new Label("code"), 0, 0);
grid.add(code, 1, 0);
grid.add(new Label("name"), 0, 1);
grid.add(name, 1, 1);

dialog.getDialogPane().setContent(grid);
dialog.setResultConverter(value -> {
if (value == addButtonType) {
return new Batch() {
{
setCode(code.getText());
setName(name.getText());
}
};
} else {
return null;
}
});

Optional<Batch> result = dialog.showAndWait();


result.ifPresent(consumer -> {
Batch batch = (Batch) consumer;
batch.getClass(); // Doesn't returns Batch class
});
}

因此,当我尝试通过对话框类返回时,它不会返回 Batch。问题是如何获取Batch类?

Batch 类的主体如下

@Entity
public class Batch {
@Id
@GeneratedValue(generator="uuid")
@GenericGenerator(name="uuid", strategy="uuid2")
@Column(name="batch_id")
private String uuid;
@NotNull(message="Code field could not be an empty")
@Column(unique=true)
private String code;
private String name;

@OneToMany(mappedBy = "batch", cascade = CascadeType.ALL)
private Collection<Product> products = new ArrayList<Product>();

public Collection<Product> getProducts() {
return products;
}

public void setProducts(Collection<Product> products) {
this.products = products;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getUuid() {
return uuid;
}

public void setUuid(String uuid) {
this.uuid = uuid;
}

}

最佳答案

您创建扩展Batch的匿名类的实例。替换您的 if 语句

if (value == addButtonType) {
return new Batch() {
{
setCode(code.getText());
setName(name.getText());
}
};
}

使用以下代码:

    if (value == addButtonType) {
Batch b = new Batch();
b.setCode(code.getText());
b.setName(name.getText());
return b;
}

关于Java getClass 返回不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27792616/

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