Question

Let's say:

I have a Class Animal and I want to create an instance of that class by the name "bird". "bird" is stored in a String.

How to do that?

String variable_name = "bird";

I want to use the string in variable_name as an Animal's instance.

Animal bird = new Animal();

Thanks...

Was it helpful?

Solution

You can do this with the reflection

public class DynamicSetTest {

    private Animal animal1 = null;
    private Animal animal2 = null;
    private Animal animal3 = null;

    public Animal getAnimal1() {
        return animal1;
    }
    public Animal getAnimal2() {
        return animal2;
    }
    public Animal getAnimal3() {
        return animal3;
    }

    public void setField(String name, Animal value) throws Exception {
            Field field = this.getClass().getDeclaredField(name);
            field.set(this, value);
    }

    public static void main(String[] args) throws Exception {
        DynamicSetTest t = new DynamicSetTest();
        Animal anAnimal = new Animal();
        t.setField("animal3", anAnimal);
        assert t.getAnimal3() == anAnimal;
    }
}

Note that you have a field for each possible name. You also have to handle the case if the variable doesn't exist.

I'm wondering if you instead want to use a Map and add objects using that name like

Map<String, Animal> animals = new HashMap<String, Animal>();
animals.put("animal3", anAnimal);
assert animals.get("animal3") == anAnimal;

OTHER TIPS

Add name as a field in Animal and ask for it in the constructor.

class Animal {

    String name;

    public Animal(String name) {
        this.name = name;
    }
}

Then when you construct an animal use:

Animal bird = new Animal("bird");
Animal deer = new Animal("deer");
Animal wumpus = new Animal("wumpus");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top