java - 如何在 Java 中使用用户输入引用类型、对象名称和参数在运行时创建对象

标签 java oop object

我希望能够根据用户输入动态创建员工对象。我已经开设了两个不同的类(class),一个是经理,一个是助理。我应该能够输入我想要创建的员工类型以及员工的姓名和年龄。 我怎样才能做到这一点?

while (true){

System.out.print("Input the type of employee: "); 

String type = Input.next();

//Can only be "manager" or "associate"


System.out.print("Input the name of the employee: ");

String name = Input.next();

System.out.print("Input the age of the employee: ");

int age = Input.nextInt();


/*The name of the object should also be the name of the employee
*Depending on what "Type" is given from the user determines what type of object the new object is going to be 
*/

type name = new type(name,age)

//type is not the reference type but a variable holding the reference *type
*/
}

我希望我能够创建任意数量的引用类型的对象:管理器或关联器。不同的名字和年龄

最佳答案

不能使用字符串变量作为类名。而不是

type name = new type(name,age)

尝试

if ("manager".equals(type)) {
    Manager mgr = new Manager(name, age);
} else {
    Associate asc = new Associate(name, age);
}

这假设您在某处定义了 ManagerAsssociate 类,并且它们每个都有一个采用 String 的构造函数int.

关于java - 如何在 Java 中使用用户输入引用类型、对象名称和参数在运行时创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58695574/

相关文章:

Thread.sleep() 的 Java 性能问题

PHP:单例与静态类

c++ - 正确的 "polymorphic"方式存储枚举,有时存储一些数据

arrays - 在 swift 3 中本地存储类对象

javascript - 从对象生成的 dat.GUI

java - 使用 mvn 命令部署 Maven 应用程序时出现问题

java - 具有相同名称的 Jaxb 对象

java - 将excel的内容写入文本文件

java - 重构代码以尊重 OOP 原则

javascript - for 循环中的 If-else 不起作用 - Javascript