三种获取方法
- 方式1: 通过类名.class获得
- 方式2:通过对象名.getClass()方法获得
- 方式3:通过Class类的静态方法获得: static Class forName(“类全名”)
- 每一个类的Class对象都只有一个。
示例代码
package com.itheima._03反射;
public class Student{
}
public class ReflectDemo01 {
public static void main(String[] args) throws ClassNotFoundException {
// 获得Student类对应的Class对象
Class c1 = Student.class;
// 创建学生对象
Student stu = new Student();
// 通过getClass方法
Class c2 = stu.getClass();
System.out.println(c1 == c2);
// 通过Class类的静态方法获得: static Class forName("类全名")
Class c3 = Class.forName("com.itheima._03反射.Student");
System.out.println(c1 == c3);
System.out.println(c2 == c3);
}
}