Java基础(三)反射和Class

一、简介

Java反射是Java被视为动态语言的一个关键性质,这个机制允许程序在运行时透过Reflection APIs取得任何一个已知名称的class的内部信息,包括其modifiers(诸如public, static 等)、superclass(例如Object)、实现之interfaces(例如Cloneable),也包括fields和methods的所有信息,并可于运行时改变fields内容或唤起methods。

二、原理

反射找到类信息的过程:

1)通过类的全限定名可以找到该类的Class对象;

2)通过Class对象可以查到该类的方法、成员变量等信息,最底层调用的是native方法查询clss文件中的内容;

3)如果Class对象的ReflectionData数据体为空,则从JVM中获取;

Class对象:Class<?> refClass = Class.forName("test.ReflectionTest);

// Class对象中的ReflectionData
static class ReflectionData<T> {
   volatile Field[] declaredFields;
   volatile Field[] publicFields;
   volatile Method[] declaredMethods;
   volatile Method[] publicMethods;
   volatile Constructor<T>[] declaredConstructors;
   volatile Constructor<T>[] publicConstructors;
   volatile Field[] declaredPublicFields;
   volatile Method[] declaredPublicMethods;
   final int redefinedCount;

   ReflectionData(int redefinedCount) {
      this.redefinedCount = redefinedCount;
   }
}

猜你喜欢

转载自blog.csdn.net/ss1300460973/article/details/85539454
今日推荐