java中获得Class类有三种方式,我们定义一个Person类如下:
package Person;
public class Person {
private int id;
private String name;
private int age;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
主函数调用方法如下:
package reflectDemo;
import person.Person;
public class ReflectDemo {
public static void main(String[] args) throws ClassNotFoundException {
//1.类名.class
Class<Person> clazz1 = Person.class;
System.out.println(clazz1);
//2.Class.forName("")
Class<Person> clazz2 = (Class<Person>) Class.forName("person.Person");
System.out.println(clazz2);
//3.对象.getClass();
Person person = new Person();
Class<Person> clazz3 = (Class<Person>) person.getClass();
System.out.println(clazz3);
//查看是否为同一个class文件
System.out.println(clazz1==clazz2);
System.out.println(clazz1==clazz3);
}
}
打印结果如图所示,说明他们得到的都是同一个.class文件