获取Class类的三种方式

获取Class类的三种方式

  1. 通过类名.class获取
  2. 通过实例对象获取
  3. 通过Class.forName获取
    三种方式获取的类是同一个,应为它们的hsahCode相同
public class Test01 {
    public static void main(String[] args) throws ClassNotFoundException {
        //方式一:通过类名获取
        Class c1=Person.class;
        //方式二:通过对象获取
        Person person= new Person();
        Class c2 = person.getClass();
        //通过类获取
        Class c3 = Class.forName("com.reflection.Person");

        //三种方式获取的类是同一个
        System.out.println(c1==c2);
    }
}
class Person{
    String name;
    int age;
}

版权声明:本文为qq_46173719原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。