package com.kuang.reflection;
/**
* @author 曲志鹏
* @version 1.0
* @2021/8/14 19:13
*/
public class Test03 {
public static void main(String[] args) throws ClassNotFoundException {
Person person= new Student();
System.out.println("这个人是:"+person.name);
//通过对象获得
Class<? extends Person> c1 = person.getClass();
//forname 获得
System.out.println(c1.hashCode());
Class<?> c2 = Class.forName("com.kuang.reflection.Student");
System.out.println(c2.hashCode());
//通过类名.class获得
Class<Student> c3 = Student.class;
System.out.println(c3.hashCode());
//内置类型的包装类都有一个Type属性
Class<Integer> c4 = Integer.TYPE;
System.out.println(c4);
//获得父类类型
Class<?> c5 = c1.getSuperclass();
System.out.println(c5);
}
}
class Person{
public Person(String name) {
this.name = name;
}
String name;
public Person(){
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class Student extends Person{
public Student(){
this.name="学生";
}
}
class Tercher extends Person{
public Tercher(){
this.name="老师";
}
}
1)前提:若已知具体的类,通过类的class属性获取,该方法最为安全可靠, 程序性能最高 实例:Class clazz = String.class;
2)前提:已知某个类的实例,调用该实例的getClass()方法获取Class对象 实例:Class clazz = “www.atguigu.com”.getClass();
3)前提:已知一个类的全类名,且该类在类路径下,可通过Class类的静态方 法forName()获取,可能抛出ClassNotFoundException 实例:Class clazz = Class.forName(“java.lang.String”);
其他方式(不做要求) ClassLoader cl = this.getClass().getClassLoader(); Class clazz4 = cl.loadClass(“类的全类名”);