![](/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.