简体   繁体   中英

convert string input to instance of object name(=input)

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...

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.

I suggest you make Animal an abstract class and introduce a AnimalFactory which creates you the required types (this Factory may use a switch). You could as well introduce an Enum AnimalTypes instead of your String representation.

public class AnimalFactory {

    public Animal create(AnimalType animal) {
        switch (animal) {
            case lion: return new lion(); break;
            case dog: return new dog(); break;
            default: break;
        }
    }
}

Your 'animals' all extend the abstract class Animal .

Technically this should work for you, this is just a snippet not sure if it works, if you encounter issues, add comment and I'll make it more generic

Map<String, Class> classes = new HashMap<>();
classes.put("zebra", Zebra.class);
classes.put("lion", Lion.class);
classes.put("etc", Etc.class);

Animal aClass = classes.get(animalName).newInstance();

I guess what you want to ask is that the input name must be a class name like, if the user inputs lion then instance of lion must be created. If this is the condition then you must use java reflection. For example - Class cls = Class.forName(inputUserName); This will get you the required class. Now to create the instance for the class Object clsInstance = (Object) cls.newInstance();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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