Search code examples
javaoopreflectiondynamicjcombobox

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)

I have a method called prepPerson(Person) and it accepts a 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.

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?


Solution

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