Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get the parameter names of an object's constructors (reflection)?
    text
    copied!<p>Say I somehow got an object reference from an other class:</p> <pre><code>Object myObj = anObject; </code></pre> <p>Now I can get the class of this object:</p> <pre><code>Class objClass = myObj.getClass(); </code></pre> <p>Now, I can get all constructors of this class:</p> <pre><code>Constructor[] constructors = objClass.getConstructors(); </code></pre> <p>Now, I can loop every constructor:</p> <pre><code>if (constructors.length &gt; 0) { for (int i = 0; i &lt; constructors.length; i++) { System.out.println(constructors[i]); } } </code></pre> <p>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)</p> <p>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:</p> <pre><code>if (constructors.length &gt; 0) { for (int iCon = 0; iCon &lt; constructors.length; iCon++) { Class[] params = constructors[iCon].getParameterTypes(); if (params.length &gt; 0) { for (int iPar = 0; iPar &lt; params.length; iPar++) { Field fields[] = params[iPar].getDeclaredFields(); for (int iFields = 0; iFields &lt; fields.length; iFields++) { String fieldName = fields[i].getName(); System.out.println(fieldName); } } } } } </code></pre> <p>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!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload