获取类的数种方法

public class Demo01 {
    public static void main(String[] args) throws Exception {
        Person person = new Student();
        System.out.println("这个人是" + person.name);
        System.out.println("===================================");

        //方法一:通过对象获得类
        Class c1 = person.getClass();
        System.out.println(c1.hashCode());

        //方法二:forname获得
        Class c2 = Class.forName("Annotation.Demo02.Student");
        System.out.println(c2.hashCode());

        //方法三:  通过类名.class获得
        Class c3 = Student.class;
        System.out.println(c3.hashCode());

        //方法四,基本内置类型的包装类,都有一个Type属性
        Class c4 = Integer.TYPE;
        System.out.println(c4.hashCode());
        System.out.println(c4);

        //获得父类类型
        Class c5 = c1.getSuperclass();
        System.out.println(c5.hashCode());
        System.out.println(c5);

    }
  • 父类
public class Person {
    String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "person{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • 子类

public class Student extends Person {
    public Student(){
        this.name="学生";
    }
}
posted @ 2022-02-25 15:34  小幼虫虫  阅读(52)  评论(0)    收藏  举报