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 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);
}
}