获取类对象三种方式:
- source源代码阶段:Class.forname(“全类名”);//多用于读取配置文件加载类的时候
- Class类对象阶段(加载进内存):类名.class //多用于参数传递的时候
- Runtime运行时阶段:对象.getClass(); //多用于对象获取字节码的方式
- 同一个字节码文件(.class)在一次程序运行过程中只会加载一次
- 不论通过哪一种方式获取的class对象都是同一个,即在堆中的地址相同
测试代码
public class Reflect_getClass {
public static void main(String[] args) throws ClassNotFoundException {
Class cla1 = Class.forName("web01_反射.Student");
Class cla2 = Student.class;
Student stu = new Student();
Class cla3 = stu.getClass();
System.out.println(cla1 == cla2);//true
System.out.println(cla1 == cla3);//true
System.out.println(cla2 == cla3);//true
}
}