What is Class.forName() in Java

The Class.forName() in Java or java.lang.Class.forName(String className) method returns the Class object associated with the class or interface with the given string name.

Given the fully qualified name for a class or interface (in the same format returned by getName()), this method attempts to locate, load, and link the class or interface.

The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.

If name denotes a primitive type or void, an attempt will be made to locate a user-defined class in the unnamed package whose name is name.

Therefore, this method cannot be used to obtain any of the Class objects representing primitive types or void.

If name denotes an array class, the component type of the array class is loaded but not initialized.

A typical example is the JDBC API which loads, at runtime, the exact driver required to perform the work. EJBs containers, Servlet containers are other good examples and they use dynamic runtime loading to load and create components at the runtime.

Note that this feature is not required for JDBC 4.0 as it has auto-loading feature.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *