@[TOC]
2.2.4 获取Class对象的三种方式
首先来进行了解一下Class类。Class对象是Java类反射的基础,包含了与类相关的信息。进入Class对象的源码进行查看,可以发现Class对象就是java.lang.Class这个类生成的对象,其中类型参数T表示由该Class建模的类的类型。比如说:User.class的类型就是Class。如果被建模的对象类型未知,则用?号代替,例如Class<?>。
我们可以看Class类的源码,来对Class对象进行进一步的了解。下面代码是Class源码上的注释。
/**
* Instances of the class {@code Class} represent classes and
* interfaces in a running Java application. An enum is a kind of
* class and an annotation is a kind of interface. Every array also
* belongs to a class that is reflected as a {@code Class} object
* that is shared by all arrays with the same element type and number
* of dimensions. The primitive Java types ({@code boolean},
* {@code byte}, {@code char}, {@code short},
* {@code int}, {@code long}, {@code float}, and
* {@code double}), and the keyword {@code void} are also
* represented as {@code Class} objects.
*
* <p> {@code Class} has no public constructor. Instead {@code Class}
* objects are constructed automatically by the Java Virtual Machine as classes
* are loaded and by calls to the {@code defineClass} method in the class
* loader.
对于英文水平好的读者,建议直接读英文原文。我这里简单的翻译前面两段。
Class类的实例表示正在运行的 Java应用程序中的类和接口。枚举是一种类,注释是一种接口。每个数组也属于一个被映射为Class对象的类,所有具有相同元素类型和维数的数组都共享该Class对象。基本的Java类型(boolean、byte、char、short、int、long、float和double)和关键字void也表示为Class对象。
Class没有公共构造方法。Class对象是在加载类时由Java虚拟机以及通过调用类加载器中的defineClass方法自动构造的。
......
更多内容请阅读原文:
https://chenhx.blog.csdn.net/article/details/107923538