gpt4 book ai didi

java - 新的Object.getClass()

转载 作者:行者123 更新时间:2023-12-02 08:23:27 25 4
gpt4 key购买 nike

有没有办法创建另一个对象类型的新对象?

示例:

Soldier extends Person
Accountant extends Person

Person 的每个子类都有一个接受(出生日期和死亡日期)的构造函数

我有一个名为 prepPerson(Person) 的方法,它接受一个 Person。我想要一个 JComboBox 填充不同类型的 Person 对象(会计、士兵),我调用 .getSelectedItem() 并返回一个 Person 对象。

由于我仅使用这些 Person 对象来填充 JComboBox 菜单,因此如何检测所选人员的类型,创建一个新的 Soldier 或 Accountant 对象,以便我可以将其传递给 prepPerson 方法?

最佳答案

如果您的选择数量有限,请执行以下操作:

Person thePerson = null; // note, don't call variables theAnything... it's just bad

JComboBox theBox = new JComboBox(new String[]{"Accountant","Soldier","Programmer"});



// later

public void actionPerformed(ActionEvent e) {
if(e.getSource() == theBox) {
String who = (String)theBox.getSelectedItem();
if(who.equals("Accountant") thePerson = new Accountant();
if(who.equals("Soldier") thePerson = new Soldier();
if(who.equals("Programmer") thePerson = new Programmer();
}
}

关于java - 新的Object.getClass(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5019625/

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