![](/img/trans.png)
[英]How do I build a Java type object at runtime from a generic type definition and runtime type parameters?
[英]How to create an object during runtime with user input reference type, object name and parameters in Java
我希望能够根据用户输入动态创建员工 object。 我有两个不同的班级,一个是经理,一个是助理。 我应该能够输入我想要创建的员工类型以及员工的姓名和年龄。 我怎样才能做到这一点?
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
*/
}
我希望我应该能够创建任意数量的引用类型的对象:管理器或关联。 有不同的名字和年龄
您不能将字符串变量用作 class 名称。 代替
type name = new type(name,age)
尝试
if ("manager".equals(type)) {
Manager mgr = new Manager(name, age);
} else {
Associate asc = new Associate(name, age);
}
这假设您在某处定义了类Manager
和Asssociate
,并且它们每个都有一个构造函数,该构造函数接受一个String
和一个int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.