简体   繁体   English

新的Object.getClass()

[英]new Object.getClass()

Is there a way to make a new Object of the type of another? 有没有办法制作另一种类型的新对象?

Example: 例:

Soldier extends Person
Accountant extends Person

Each subclass of Person has a constructor that accepts (BirthDate and DeathDate) Person的每个子类都有一个接受(BirthDate和DeathDate)的构造函数

I have a method called prepPerson(Person) and it accepts a Person. 我有一个名为prepPerson(Person)的方法,它接受一个Person。 I would like to have a JComboBox populated with Person objects of different types (Accountant, Soldier) that I call .getSelectedItem() and get back a Person object. 我想要一个JComboBox填充不同类型的Person对象(Accountant,Soldier),我调用.getSelectedItem()并返回一个Person对象。

As I am only using those Person objects to populate the JComboBox menu how do I detect the type of person selected, make a new Soldier or Accountant object so that I can pass it to the prepPerson method? 因为我只使用那些Person对象来填充JComboBox菜单,如何检测所选人员的类型,创建一个新的Soldier或Accountant对象,以便我可以将它传递给prepPerson方法?

Use either instanceof or create method getType() on Person which return enum - the type of the Person . Person上使用instanceof或create方法getType()返回枚举 - Person的类型。

But when you start using instanceof in such situation you may consider to change the desing somehow. 但是当你在这种情况下开始使用instanceof时,你可能会考虑以某种方式改变设计。

Could you describe why do you need to distinguish them later? 你能描述一下为什么以后需要区分它们吗?

If you're going to have a finite number of selections, do this: 如果您要进行有限数量的选择,请执行以下操作:

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

Why do you need to detect the type? 为什么需要检测类型? You have a Person and you must pass a Person to the new method. 您有一个Person ,您必须将Person传递给新方法。

You are likely to find seperating Roles/Types from a Person useful. 你可能会找到有用的一个人角色分隔条件/类型。 This way any Person can have one or more roles which can change at any time. 这样,任何人都可以拥有它可以在任何时候改变一个或多个角色。

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

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