What is the purpose Class.forName method?
What is the purpose Class.forName method?
The Class.forName
method in Java serves a fundamental purpose of dynamically loading a class at runtime. This method returns the Class
object associated with the class or interface with the given string name, which is provided as a parameter. The name should be the fully qualified name of the desired class.
When Class.forName
is invoked, it does two main things:
Loads the Class: It locates, loads, and links the class or interface represented by the string parameter. The loading is done by the class loader of the current thread if no class loader is explicitly specified.
Initializes the Class: If the class has not been previously initialized, Class.forName
will also initialize the class. This means that all static initializers and static initialization blocks are executed. This is particularly important for setting up a class's environment before it is used within the program.
The method is often used in scenarios where the class name is not known at compile time and can only be determined at runtime. This is common in many design patterns, such as Factory patterns, where the implementation class to be loaded can vary based on configuration or user input.
Additionally, Class.forName
has been historically significant in loading JDBC drivers. JDBC drivers typically register themselves in their static initializer blocks. By calling Class.forName
with the driver's class name, the driver registers itself with the `DriverManager...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào