黑马程序员技术交流社区

标题: 反射中的getConstructors()方法 [打印本页]

作者: lwy0319    时间: 2014-3-28 06:26
标题: 反射中的getConstructors()方法
      怎么准确的提取出getConstructors()返回的Constructor[]数组元素?感觉用为什么脚标的排序跟我定义的顺序不同?如果不用脚标还有别的办法将我想要的构造提取出来么?代码如下:
  1. package reflect;

  2. import java.lang.reflect.Constructor;
  3. import java.lang.reflect.InvocationTargetException;
  4. class Test{
  5.         private int i;
  6.         public int getI(){
  7.                 return this.i;
  8.         }
  9.         public Test(){this.i=0;}//定义Test接收不同参数类型的构造方法
  10.         public Test(int a){this.i=1;}
  11.         public Test(String b){this.i=2;}
  12.         public Test(int a,String b){this.i=3;}
  13. }
  14. public class ReflectDemo3 {

  15.         public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
  16.                 Constructor[] constructor=Test.class.getConstructors();
  17.                 for(Constructor c:constructor)
  18.                 System.out.println(c);
  19.         }
  20. }
复制代码

运行结果:
public reflect.Test(java.lang.String)
public reflect.Test(int,java.lang.String)
public reflect.Test()
public reflect.Test(int)
跟我定义的顺序不同,既不是正数也不是倒数,那怎么才能准确定位Constructor[]中的元素呢?
作者: haixian    时间: 2014-3-28 08:53
public Constructor<T> getConstructor(Class<?>... parameterTypes)你可以通过这个方法得到具体的构造函数。
作者: lwy0319    时间: 2014-3-28 16:12
haixian 发表于 2014-3-28 08:53
public Constructor getConstructor(Class... parameterTypes)你可以通过这个方法得到具体的构造函数。 ...

呃。。谢谢,。。我现在倒不发愁怎么提取我想要的构造函数这一目的。。主要好奇这个方法是怎么定义的,每次运行结果都一样,按我的构造方法的声明循序,它每次的遍历顺序都是2、3、0、1,(我最后声明的构造方法在其数组下的脚标是1,而最先声明无参构造方法在其下的脚标是2)
作者: 蒋珍珍    时间: 2014-4-1 10:18
我的电脑上实验结果是按照了你定义的构造方法的声明顺序排的。
我调试了一下,对于返回的这些对象数组底层用到了StringBuffer这个容器,逐步保存构造方法的修饰符modifier/参数列表,最后调用sb.toString()打印出来。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2