![]() ![]() If you have obtained an object, and you want to obtain the class object of this object, you can achieve it using the method below: If you know the class name during the compilation stage, you can obtain a class object using the method below. All Java class types, including the basic class type such as an array, have associated class objects. Reflection class and construct an objectīefore proceeding to check out the information about a class, first you should obtain the class object. In the sections below, we will demonstrate some frequently-used reflection APIs and try to explain reflection from the perspective of code.Ģ. By creating “new” objects, we are actually creating objects using these classes, only that this process is not transparent to us. ![]() 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. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |