繁体   English   中英

新的Object.getClass()

[英]new Object.getClass()

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

例:

Soldier extends Person
Accountant extends Person

Person的每个子类都有一个接受(BirthDate和DeathDate)的构造函数

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

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

Person上使用instanceof或create方法getType()返回枚举 - Person的类型。

但是当你在这种情况下开始使用instanceof时,你可能会考虑以某种方式改变设计。

你能描述一下为什么以后需要区分它们吗?

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

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

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

你可能会找到有用的一个人角色分隔条件/类型。 这样,任何人都可以拥有它可以在任何时候改变一个或多个角色。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM