Class类对象的三种实例化方式
1. 通过对象实例化
1 class Person { 2 3 } 4 public class Test { 5 public static void main(String[] args) throws ClassNotFoundException { 6 Person person = new Person(); 7 Class<? extends Person> cls = person.getClass(); 8 System.out.println(cls.getName()); 9 System.out.println(cls); 10 } 11 }
先实例化对象,通过对象.getClass方法实例化
2. 由于1中必须要先有对象,所以在没有对象的情况下,可以通过类名称.class方式
1 class Person { 2 3 } 4 public class Test { 5 public static void main(String[] args) throws ClassNotFoundException { 6 Class<? extends Person> cls = Person.class; 7 System.out.println(cls.getName()); 8 System.out.println(cls); 9 } 10 }
3. 通过Class类中的静态方法
1 class Person { 2 3 } 4 public class Test { 5 public static void main(String[] args) throws ClassNotFoundException { 6 Class<?> cls = Class.forName("fanshe.Person"); 7 System.out.println(cls.getName()); 8 System.out.println(cls); 9 } 10 }