4

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?

1
  • 2
    Java bytecode doesn't contain names of args Commented Mar 25, 2013 at 7:52

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

Is this the same for methods? Method names cannot be retrieved?
@user2023359: Method names -- yes. Argument names -- no.
1

Name is not available via reflection in JAVA.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.