Java 新对象。getClass()

Java 新对象。getClass(),java,oop,reflection,dynamic,jcombobox,Java,Oop,Reflection,Dynamic,Jcombobox,有没有办法制作另一种类型的新对象 例如: Soldier extends Person Accountant extends Person Person的每个子类都有一个接受(生日和死亡日期)的构造函数 我有一个名为prepPerson(Person)的方法,它接受一个人。我希望JComboBox中填充不同类型的Person对象(会计、士兵),我调用.getSelectedItem()并返回Person对象 由于我只使用这些Person对象来填充JComboBox菜单,如何检测所选人员的类型,

有没有办法制作另一种类型的新对象

例如:

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

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


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

为什么需要检测该类型?您有一个
,必须将
传递给新方法


你可能会发现,从一个人身上分离角色/类型很有用。这样,任何人都可以有一个或多个角色,这些角色可以随时更改。

使用
instanceof
或在
Person
上创建方法
getType()
,返回enum-Person的类型

<>但是,当你开始使用<代码>实例> <代码>时,你可以在某种程度上考虑改变设计。p>
您能描述一下为什么以后需要区分它们吗?

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

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();
        }
}

另一方面,@Jan Zyka回答说,您还可以将
类PersonRole
作为您的个人元素。在本例中,如果(who.equals(“accounter”))person.addRole(newaccountrole()),您可以执行
(实际上,在这种情况下,我会将
字符串who
更改为
字符串what
!:)我需要类型,这样我就可以找到合适的人,这样我就可以调用该类的构造函数,这样我就可以从该对象创建一个新对象,以避免为所有这些类编写复制构造函数。你能让这些类可以克隆吗?(如果您只想复制它们)您可以使用反射从类中获取构造函数,但这相对来说比较难看。