java注解和反射(反射:第一部分)

 

 

 

 

 

 

 

 

/**
* 获取class类实例的方式
*/
public class Test04 {
public static void main(String[] args) throws ClassNotFoundException {
Persion persion = new Teacher();
Persion persion2 = new Teacher();
System.out.println("这个人是"+persion.name);//这个人是老师

//方式一、通过对象获得
Class c1 = persion.getClass();
Class c12 = persion2.getClass();
System.out.println(c1.hashCode());//460141958
System.out.println(c12.hashCode());//460141958
System.out.println("========================================");

///方式二、通过类名获取
Class c2 = Teacher.class;
System.out.println(c2.hashCode());//460141958

//方式三、forname获取
Class c3 = Class.forName("javaBasic.annotation.Teacher");
System.out.println(c3.hashCode());//460141958

//前三种方式获得的class类实例的hashcode一致,表明一个类只有一个class类实例。

//方式四、基本类型的包装类都有一个Type类型
Class c4 = Integer.TYPE;
System.out.println(c4.hashCode());//1163157884

//获得父类类型
Class superclass = c1.getSuperclass();
System.out.println(superclass);//class javaBasic.annotation.Persion

}
}
class Persion{
public String name;

@Override
public String toString() {
return "Persion{" +
"name='" + name + '\'' +
'}';
}
}
class Teacher extends Persion{
public Teacher(){
this.name = "老师";
}
}
class Student extends Persion{
public Student(){
this.name = "学生";
}
}

 

posted @ 2022-05-05 16:13  花田007  阅读(23)  评论(0编辑  收藏  举报