A Java program can be dynamically extended by using following two APIs:
- The forName() method of java.lang.Class class, or
- The loadClass() method of an instance of a user-defined class loader.
The forName() method has two overloaded signatures:
- public static Class<?> forName(String className) throws ClassNotFoundException
- Returns the Class object associated with the class or interface with the given string name.
- Returns the Class object associated with the class or interface with the given string name, using the given class loader. The class will be initialized if the parameter is true, and if it has not been initialized earlier. If loader parameter is passed as null then it means request is to load class from bootstrap class loader.
The loadClass() method has two overloaded signatures:
- public Class<?> loadClass(String name) throws ClassNotFoundException
- Loads the class with the specified binary name. If the class is already loaded then it returns the Class instance representing that already-loaded type. If not then is loaded via some customized way decided by the user-defined class loader.
- Loads the class with the specified binary name. The resolve parameter indicates whether or not the type should be linked as well loaded.
Now it should be clear whether you should use forName() or loadClass(); as it depends on your need; if you have no special needs which requires class loader, you should use forName(); also when you want class to be initialized use forName() with right signature. Class loaders can help you have some custom way of loading types, such as by downloading them across a network, retrieve from a DB, from an encrypted file, or even generating them on the fly.
Initialization is the reason, for example, why JDBC drivers generally loaded with a call to forName(). Because the static initializers of driver class register the driver with a DriverManager.
Note:Linking process involves three steps:
- verification of the loaded type;
- preparation, which involves allocating more memory for the type; and
- optionally, resolution of symbolic references contained into the type.