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;
Animalthat when accessed would return"bird", or do you want to have the actual instance name of theAnimalbe based on some value in aString, in this casebird?Animaland assign it to the field with name 'variable_name' ?