I have a lot of classes and I want the user to type a name and he will get instance of the same name of a specific object (class). I simplify it by this code:
public class Animal {...}
public class lion extends Animal{...}
public class zebra extends Animal{...} // and so on for a lot of animals
String name = input from user
Animal something = new Animal(instance of the input name)
At the last line I actually wanted to convert the string name to be instance of a class name. Is there any way to do it? there is going to be a lot of animals so i don't want to write a lot of switch cases as: "if input equals to lion" or zebra or snake or...
We can also convert the string to an object using the Class. forName() method. Parameter: This method accepts the parameter className which is the Class for which its instance is required. Return Value: This method returns the instance of this Class with the specified class name.
Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.
In Java, a String can be converted into an Object by simply using an assignment operator. This is because the Object class is internally the parent class of every class hence, String can be assigned to an Object directly. Also, Class. forName() method can be used in order to convert the String into Object.
String Into Variable Name in Python Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.
I want the user to type a name and he will get instance of the same name of a specific object (class).
Class.forName()
is what you are looking for , if I'm not wrong ?
Returns the Class object associated with the class or interface with the given string name.
Object obj = Class.forName(user_enterd_name).newInstance();
I suggest here to create a Factory
class that create the suitable instance for you
For Example:
public class AnimalFactory {
public Animal getAnimal(String input) {
if(input.equals("lion")) {
return new lion();
} else if(input.equals("zebra")) {
return new zebra();
}
}
}
Go with that (it uses reflection):
public static Animal createAnimal(String name) {
try {
String package = "your.pkg"; // assuming all classes resume in the same package
String fqn = package + "." + name;
Class<?> animalClass = Class.forName(fqn);
return (Animal) animalClass.newInstance();
} catch (Exception e) {
return null; // react to any exception here
}
}
This code snippet requires all animal sub classes to have a default constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With