[英]Java Constructor List as string
我正在嘗試使用類的構造函數名稱填充字符串數組列表。 由於某種原因,它改為使用類名填充
Class<?> c = Class.forName(className);
Constructor<?>[] construct = c.getDeclaredConstructors();
for(int i = 0; i < construct.length; i++){
memberList.add(construct[i].getName());
}
構造函數始終使用類的名稱-這就是您所看到的。
如果要在列表中使用構造器對象而不是構造器對象的名稱 ,則需要刪除“ .getName()” 。
就像Sunil所說的那樣,構造函數與類具有相同的名稱,因此您應在檢查其參數方面區別對待。
要獲取參數,您可以嘗試以下代碼:
public static void main(String[] args) throws ClassNotFoundException {
Class<?> c = Class.forName(Class1.class.getCanonicalName());
Constructor<?>[] constructors = c.getDeclaredConstructors();
ArrayList<String> memberList = new ArrayList<String>();
for(Constructor<?> constructor:constructors){
memberList.add(constructor.getName());
System.out.println("--------------------------------------");
System.out.println(String.format("constructor: %s",new Object[]{constructor}));
for(Class<?> paramType: constructor.getParameterTypes()){
System.out.println(String.format("constructor param type: %s",paramType));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.