The forName(String, boolean, ClassLoader) method of java.lang.Class class is used to get the instance of this Class with the specified class name, using the specified class loader. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.
public static Class<T> forName(String className, boolean initialize, ClassLoader classLoader) throws ClassNotFoundException
Parameter: This method accepts following parameters:
- className which is the Class for which its instance is required.
- initialize which is the boolean to state if this class instance needs to be initialized or not.
- classLoader which is the ClassLoader from which this Class must be loaded.
Return Value: This method returns the instance of this Class fetched using the specified parameters.
Exception: This method throws following Excpetions:
- LinkageError: if the linkage fails
- ExceptionInInitializerError: if the initialization provoked by this method fails
- ClassNotFoundException: if the class cannot be located
- SecurityException: if a security manager is present, and the loader is null, and the caller’s class loader is not null, and the caller does not have the RuntimePermission(“getClassLoader”)
Below programs demonstrate the forName() method.
Class represented by c1: class java.lang.String
Class represented by c1: class java.lang.Integer
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.