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

我希望能够根据用户输入动态创建员工对象。我有两种不同的课程,一种已经成为经理,另一种已经成为经理。我应该能够输入要创建的员工类型以及该员工的姓名和年龄。 我该怎么办?

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
*/
}

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

Jasonxxxyyy 回答:如何在运行时使用Java中的用户输入引用类型,对象名称和参数创建对象

不能将String变量用作类名。代替

<script src="http://unpkg.com/GLSlideshow@2.1.0/dist/gl-slideshow.js"></script>
<canvas id="myCanvas"></canvas>

尝试

type name = new type(name,age)

这假设您在某个位置定义了类if ("manager".equals(type)) { Manager mgr = new Manager(name,age); } else { Associate asc = new Associate(name,age); } Manager,并且它们每个都有一个构造函数,该构造函数采用AsssociateString

本文链接:https://www.f2er.com/3165953.html

大家都在问