Static and dynamic class loading?

Why do I need to load a class definition, for example:

Class.forName ("ClassName");

What is the need and advantage of this. Typically, what is used to load the driver class into JDBC.

+7
java oop
source share
3 answers

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.

+10
source share

In fact, you are not doing this. ClassName.class will work just as well. In any case, the definition of a class this way, as a rule, is that SPIs are implemented in .

+1
source share

The simplest reason to use Class.forName (string className) is

  • In JDBC, the operator is used to download and register DriverClass using the DriverManager. Another way to do this is to use the registerDriver (Driver obj) method, which accepts an object of the driver.Using class. The above statement helps us to avoid calling the driver object directly.
  • Most applications use property files to define JDBC connections and driver properties. This type of dynamic loading helps us make the application more portable, as the driver can be configured without changing the source .
0
source share

All Articles