反射——获取Class类对象

时间:2020-06-20 22:29:40   收藏:0   阅读:96

技术图片

public class ReflectDemo {
    public static void main(String[] args) throws ClassNotFoundException {
        //1.使用类的class属性来获取该类对应的Class对象。
        Class<Student> c1 = Student.class;
        System.out.println(c1);
        System.out.println("--------");
        
        //2.调用对象的getClass()方法,返回该对象所属类对应的Class对象
        Student student = new Student();
        Class<? extends Student> c2 = student.getClass();
        System.out.println(c1 == c2);
        System.out.println("--------");

        //3.使用Class类中的静态方法forName(String className)
        Class<?> c3 = Class.forName("com.reflect_02.Student");
        System.out.println(c1 == c3);
    }
}

技术图片

 

 通过c1来获取Class对象,调用其他两个方法进行比较,结果为true说明方法调用的结果都相同。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!