After a class is loaded, Java virtual machine will automatically generate a class object in memory. These class files will be loaded to the virtual machines by ClassLoader during program runtime. These class objects carry the raw information of this class type such as the parent class, interface, constructor, method and attribute. Now that we see how reflection can be used to manipulate the class information, what is a class?Īfter we compile a Java project, all the Java files will be compiled into a. This is also a typical application scenario of reflection. For example, in the Object/Relational Mapping (ORM) framework, we can only obtain the various attributes of the class at runtime, and then we obtain the class’s attribute name and value through reflection and store the data into the database. This is a common scenario for reflection usage.Īnother common scenario is that we have no idea about the internal information about the class at compilation, and such information is only available at class runtime. As a result, we can only use the classes that will exist during runtime through reflection (such classes comply with certain rules, such as JDBC). Under some circumstances, we can only determine the class to be used at runtime, and cannot use the class during the compilation phase. This ability of “penetrating the class” is called introspection and is vital during framework development. Even if a method or an attribute is private, it can be called through reflection. Reflection also enables us to instantiate objects, call methods and obtain variable values by calling get/set methods at runtime. Java Reflection is a mechanism that enables us to obtain internal information about a class such as class functions, attributes, parent classes and interfaces at runtime.
0 Comments
Leave a Reply. |