How to get the parameter names of an object's constructors (reflection)?
- by Tom
Say I somehow got an object reference from an other class:
Object myObj = anObject;
Now I can get the class of this object:
Class objClass = myObj.getClass();
Now, I can get all constructors of this class:
Constructor[] constructors = objClass.getConstructors();
Now, I can loop every constructor:
if (constructors.length > 0)
{
for (int i = 0; i < constructors.length; i++)
{
System.out.println(constructors[i]);
}
}
This is already giving me a good summary of the constructor, for example a constructor public Test(String paramName) is shown as public Test(java.lang.String)
Instead of giving me the class type however, I want to get the name of the parameter.. in this case "paramName". How would I do that? I tried the following without success:
if (constructors.length > 0)
{
for (int iCon = 0; iCon < constructors.length; iCon++)
{
Class[] params = constructors[iCon].getParameterTypes();
if (params.length > 0)
{
for (int iPar = 0; iPar < params.length; iPar++)
{
Field fields[] = params[iPar].getDeclaredFields();
for (int iFields = 0; iFields < fields.length; iFields++)
{
String fieldName = fields[i].getName();
System.out.println(fieldName);
}
}
}
}
}
Unfortunately, this is not giving me the expected result. Could anyone tell me how I should do this or what I am doing wrong? Thanks!