简体   繁体   中英

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?

您已经拥有类型,并且无法获取名称(因为它们不会作为字节码的一部分保留)。

名称在JAVA中无法通过反射获得。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM