概述
反射(reflection)
Java的反射是指程序在运行期可以拿到一个对象的所有信息
使用方法
获取对象有四种方法
实例
public class Demo02 {
public static void main(String[] args) throws ClassNotFoundException {
Student student = new Student();
System.out.println("这个人是: "+student.name);
// 方式一 通过对象获得
Class c1 = student.getClass();
System.out.println(c1.hashCode());
// 方式二 forname获得
Class c2 = Class.forName("com.gbhh.reflections.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);
// 获取父类类型
Class c5 = c1.getSuperclass();
System.out.println(c5);
}
}
class Person{
String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
}
class Student extends Person{
public Student() {
this.name = "学生";
}
}
class Teacher extends Person{
public Teacher(){
this.name = "老师";
}
}
所有类型的Class对象
public class Demo03 {
public static void main(String[] args) {
Class c1 = Object.class; //类
Class c2 = Comparable.class; //接口
Class c3 = String[].class; //一维数组
Class c4 = int[][].class; //二维数组
Class c5 = Override.class; //注解
Class c6 = ElementType.class; //枚举
Class c7 = Integer.class; //基本数据类型
Class c8 = void.class; //void
Class c9 = Class.class; //Class
// 按住alt垂直选择,复制粘贴同一列的数据
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
System.out.println(c4);
System.out.println(c5);
System.out.println(c6);
System.out.println(c7);
System.out.println(c8);
System.out.println(c9);
}
}