What is the need and advantage of this. Commonly used to load a driver class in JDBC.
It allows you to create your applications so that key external dependencies are not compiled into the application source code.
For example, in the case of JDBC, it allows you to switch between different driver implementations and (theoretically) different database providers without changing the source code.
Another use case is when a vendor develops a general form of application with extension points that allow customers to "plug in" their own custom classes. Custom classes are usually loaded using Class.forName(...) .
The third use case is application platforms and containers, which usually use Class.forName(...) under the hood to dynamically load classes for beans applications, servlets, etc.
A fourth use case is where the application (or rather the application library) has modules that are not used in a typical application launch. By using Class.forName(...) internally, an application or library can avoid the overhead of CPU and memory for loading and initializing a large number of unwanted classes. (Sun Swing libraries seem to do this to shorten application startup time, and I'm sure there are other examples.)
However, if you do not need to do this, static dependencies are easier to implement.
Followup
But here, when the "ClassName" parameter is compiled, it is known. So is the key external dependency compiled into the application source code?
Nope. Obviously, this defeats the goal. An application (or framework) usually defines the names of dynamically loaded classes from some configuration file.
Stephen c
source share