简体   繁体   English

将字符串输入转换为对象名称的实例(=输入)

[英]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 ? 如果我没错, Class.forName()就是你要找的东西?

Returns the Class object associated with the class or interface with the given string name. 返回与具有给定字符串名称的类或接口关联的Class对象。

Object obj = Class.forName(user_enterd_name).newInstance();

I suggest here to create a Factory class that create the suitable instance for you 我建议在这里创建一个Factory类,为您创建合适的实例

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). 我建议你让Animal成为一个抽象类,并引入一个AnimalFactory ,它可以创建所需的类型(这个Factory可以使用一个开关)。 You could as well introduce an Enum AnimalTypes instead of your String representation. 您也可以引入Enum AnimalTypes而不是String表示。

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 . 你的“动物”都扩展了抽象类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. 我想你要问的是输入名称必须是类名,如果用户输入lion,则必须创建lion的实例。 If this is the condition then you must use java reflection. 如果这是条件,那么你必须使用java反射。 For example - Class cls = Class.forName(inputUserName); 例如 - 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(); 现在为类Object创建实例clsInstance =(Object)cls.newInstance();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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