通过Class.forName加载自定义类,初始化调用的是无参数构造方法:
1、先定义一个类,比如Student,代码如下:
package ready.nextyear;
public class Student {
private int age;
private String name = "Alfira";
public Student() {
super();
}
public Student(int age, String name) {
super();
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;
}
}
以上是一个自定义的Student类,后面会通过Class.forName()方法来加载;
2、测试类,代码如下:
package ready.nextyear;
public class TestClassForName {
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException {
Class stu = Class.forName("ready.nextyear.Student");
Student student = (Student) stu.newInstance();
// 首字母大写,参数是类名,要求是全限定名,返回的是Class对象
System.out.println("the student name: " + student.getName() + "\n"
+ "the age is : " + student.getAge());
}
}
注意,这里没有传入任何参数初始化Student类;
3、输出结果如下:
the student name: Alfira
the age is : 0
打印的都是类的成员变量的初始值:
private int age;
private String name = "Alfira";