日期:2014-05-20  浏览次数:20835 次

关于反射的一个小问题,不知道错误在哪。

package Reflect;

import java.lang.reflect.Constructor;

class Demo
{

}

class Person
{

public Person()
{

}

public Person(String name)
{
this.name = name;
}

public Person(int age)
{
this.age = age;
}

public Person(String name, int age)
{
this.age = age;
this.name = name;
}

public String getName()
{
return name;
}

public int getAge()
{
return age;
}

@Override
public String toString()
{
return "[" + this.name + "  " + this.age + "]";
}

private String name;
private int age;
}

public class Hello
{

public static void main(String[] args)
{
Class<?> demo = null;
try
{
demo = Class.forName("Reflect.Person");
} catch (Exception e)
{
e.printStackTrace();
}
Person per1 = null;
Person per2 = null;
Person per3 = null;
Person per4 = null;
// 取得全部的构造函数
Constructor<?> cons[] = demo.getConstructors();
try
{
per1 = (Person) cons[0].newInstance();
per2 = (Person) cons[1].newInstance("Rollen");
per3 = (Person) cons[2].newInstance(20);
per4 = (Person) cons[3].newInstance("Rollen", 20);
} catch (Exception e)
{
e.printStackTrace();
}
System.out.println(per1);
System.out.println(per2);
System.out.println(per3);
System.out.println(per4);

}
}


错误如下。
------最佳解决方案--------------------

运行了一下:
result:
[null  0]
[Rollen  0]
[null  20]
[Rollen  20]
没有问题

顺便问一下,你的95行是哪一行?
------其他解决方案--------------------


per1 = (Person) cons[0].newInstance();
per2 = (Person) cons[1].newInstance("Rollen");
per3 = (Person) cons[2].newInstance(20);
per4 = (Person) cons[3].newInstance("Rollen", 20); 


你能确定获取到的构造方法的顺序是按照你写的顺序???
输入不能确定,那么就是在你调用newInstnce()创建对象的时候参数列表不对
要解决这个问题还是不要获取构造方法的数组,最好是按照参数列表获取单个构造方法来创建实例
------其他解决方案--------------------
应该还有更多错误吧
------其他解决方案--------------------
帮顶,lz加油!
------其他解决方案--------------------
占用各位时间,麻烦了。
------其他解决方案--------------------
小弟真心求教,为什么没有人回答下呢。