How to get the parameter names of an object's constructors (reflection)?

Posted by Tom on Stack Overflow See other posts from Stack Overflow or by Tom
Published on 2010-04-28T12:58:05Z Indexed on 2010/04/28 13:03 UTC
Read the original article Hit count: 149

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!

© Stack Overflow or respective owner

Related posts about java

Related posts about reflection