结论: 同⼀个字节码⽂件(.class)在⼀次程序运⾏过程中,只会被加载⼀次,不论通过哪⼀种⽅式获取的Class对象 都是同⼀个。 package domain; public class Person { private String name; private int age; public String a; protected String b; String c; private String d; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } 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; } @Override public String toString() { return “Person{” + “name=’” + name + ‘’’ + “, age=” + age + “, a=’” + a + ‘’’ + “, b=’” + b + ‘’’ + “, c=’” + c + ‘’’ + “, d=’” + d + ‘’’ + ‘}’; } public void eat(){ System.out.println(“eat…”); } public void eat(String food){ System.out.println(“eat…”+food); } } package domain; public class Student { public void sleep(){ System.out.println(“sleep…”); } } Class对象功能:
获取功能:
获取成员变量们
Field[] getFields() :获取所有public修饰的成员变量
Field getField(String name) 获取指定名称的 public修饰的成员变量 //1.Class.forName(“全类名”) Class cls1 = Class.forName(“domain.Person”); System.out.println(cls1); //2.类名.class Class cls2 = Person.class; System.out.println(cls2); //3.对象.getClass() Person p = new Person(); Class cls3 = p.getClass(); System.out.println(cls3); //== ⽐较三个对象 System.out.println(cls1 == cls2);//true System.out.println(cls1 == cls3);//true //不同的字节码的Class对象不同 Class c = Student.class; System.out.println(c == cls1);//false