Câu hỏi phỏng vấn Java
Câu hỏi

What is the purpose Class.forName method?

Câu trả lời

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:

  1. 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.

  2. 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

junior

Gợi ý câu hỏi phỏng vấn

junior

What’s the difference between sendRedirect and forward methods?

expert

What is DGC? And how does it work?

middle

What is structure of Java Heap ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào