user2023359
user2023359

Reputation: 289

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?

Upvotes: 4

Views: 2246

Answers (2)

NPE
NPE

Reputation: 500903

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

Upvotes: 7

guruprasath
guruprasath

Reputation: 277

Name is not available via reflection in JAVA.

Upvotes: 1

Related Questions