问题描述
- 关于getConstructors()跑出数组异常的问题
-
package StudyOne;import java.lang.reflect.Constructor;
class students{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "我的名字叫"+this.name+"今年"+this.age+"岁";}
}public class BeansOne {
public static void main(String[] args) throws Exception{
Class clazz=Class.forName("StudyOne.students");
Constructor cons[]=clazz.getConstructors();
students s=(students) cons[0].newInstance("张三",30);
System.out.println(s);
}
}
执行后会抛出一个Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0的异常。
解决方案
- package StudyOne ----Java的包名是小写的,类似package java.util;
2.class students-----Java的类名是大写的
3.加一个构造函数
下面是可以运行的:
package com.eei.common;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
- Created by luoqi on 2016/3/14.
*/
public class Student {private String name;
private int age;public Student(String name,int age){
this.age = age;
this.name = name;
}public int getAge() {
return age;
}public void setAge(int age) {
this.age = age;
}public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}public String toString() {
return "我的名字叫" + this.name + "今年" + this.age + "岁";
}public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class clazz=Class.forName("com.eei.common.Student");
Constructor cons[]=clazz.getConstructors();
Student s=(Student) cons[0].newInstance("张三",30);
System.out.println(s);
}
}
解决方案二:
这是一个数组下标异常,我想知道他为什么会出现一个 数组下标异常。