Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor Parameters Via Java Reflection

I am using Reflection in Java. Can I please have some help to get the constructor parameter names and values?

Here is my code:

  public String getConstructors(Class aClass)
  {
  StringBuilder ClassConstructors = new StringBuilder();
  Constructor[] Constructors = aClass.getConstructors();
  String separator = System.getProperty( "line.separator" );
  for (Constructor c: Constructors)
  {
      boolean isPublic = Modifier.isPublic(c.getModifiers());
      Class[] parameterTypes = c.getParameterTypes();
      for (Class pt : parameterTypes)
      {
          System.out.println(pt.getName());
          //Field[] Fields = pt.getDeclaredFields();
          //for (Field f : Fields) 
          //{
              //System.out.println(f.getType());
          //}
      }
  }
  return ClassConstructors.toString();

}

The constructor that I am testing has the following parameters:

String Name, int Diameter

The System.out.println(pt.getName()); line of code is currently printing out the following:

java.lang.String
int

Is it possible to get the Type and Name of each of the parameters?

like image 811
user2023359 Avatar asked Oct 16 '25 04:10

user2023359


1 Answers

You already have the types, and there's no way to get the names (since they're not preserved as part of the bytecodes).

like image 131
NPE Avatar answered Oct 17 '25 17:10

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!