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 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM