Java反射(1)Class类对象的获取
public class Main {
public static void main(String[] args) {
Student student = new Student();
//获取class对象的三种方式
Class a1 = Student.class;
Class a2 = student.getClass();
try {
//写完整包名 且抛出异常
Class a3=Class.forName("Student");
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
//根据class对象生成对象实例 前提是该类有无参的构造函数
Student s1=(Student) a1.newInstance();
Student s2=(Student) a2.newInstance();
Student s3=(Student) a3.newInstance();
s1.getResult();
s1.getResult();
s1.getResult();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Student{
public Student() {
super();
}
public void getResult() {
System.out.println("getResult()");
}
}