Reputation: 131
I'm trying to populate an array list of strings with the name of the constructors for a class. For some reason it's getting populated with the class name instead
Class<?> c = Class.forName(className);
Constructor<?>[] construct = c.getDeclaredConstructors();
for(int i = 0; i < construct.length; i++){
memberList.add(construct[i].getName());
}
Upvotes: 0
Views: 472
Reputation: 3147
Like Sunil said, the constructor has the same name as the class and you should make the difference between them checking his params.
To get the params you could try the next code:
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));
}
}
}
Upvotes: 0
Reputation: 1236
You need to drop the ".getName()" if you want the Constructor object in the list instead of the name of the Constructor object.
Upvotes: 0
Reputation: 7494
Constructors always take the name of the class - which is what you are seeing.
Upvotes: 3