反射——获取Class类对象

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说明方法调用的结果都相同。

猜你喜欢

转载自www.cnblogs.com/pxy-1999/p/13170312.html
今日推荐