四种创建class对象的方法
- 先创建三个类,Person,Student,Teacher。其中Student和Teacher继承Person类
class Person{
public String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class Student extends Person{
public Student(){
this.name = "学生";
}
}
class Teacher extends Person{
public Teacher(){
this.name= "老师";
}
}
- 四种获取class对象的方法
public class Test03 {
public static void main(String[] args) throws ClassNotFoundException {
Person person = new Student();
System.out.println("这个人是:"+person.name);
//方式一:通过对象获得
Class c1 = person.getClass();
System.out.println(c1);
System.out.println(c1.hashCode());
//方式二:forname获取
Class c2 = Class.forName("com.lixv.reflection.Student");
System.out.println(c2);
System.out.println(c2.hashCode());
//方式三:通过类名.class获取
Class c3 = Student.class;
System.out.println(c3);
System.out.println(c3.hashCode());
//方式四:基本内置类型的包装类都有一个Type属性
Class c4 = Integer.TYPE;
System.out.println(c4);
}
}
运行结果:
hashcode是同一个值,说明,获取的是同一个对象
- 获取class的父类class对象
//测试创建class类的创建方式有哪些
public class Test03 {
public static void main(String[] args) throws ClassNotFoundException {
Person person = new Student();
System.out.println("这个人是:"+person.name);
//方式一:通过对象获得
Class c1 = person.getClass();
System.out.println(c1);
System.out.println(c1.hashCode());
//获得父类class对象
Class c5 = c1.getSuperclass();
System.out.println(c5);
}
}
运行结果: