2 qq 34289550 qq_34289550 于 2016.03.14 19:37 提问

关于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的异常。

2个回答

shuijieshuijie
shuijieshuijie   2016.03.14 20:10
已采纳
  1. 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);
    }
    }

qq_34289550
qq_34289550   2016.03.14 20:55

这是一个数组下标异常,我想知道他为什么会出现一个 数组下标异常。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!