Open In App

Class forName(String, boolean, ClassLoader) method in Java with Examples

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.
Syntax: 
 

public static Class<T>
 forName(String className, 
         boolean initialize, 
         ClassLoader classLoader) 
 throws ClassNotFoundException

Parameter: This method accepts following parameters: 
 



Return Value: This method returns the instance of this Class fetched using the specified parameters.
Exception: This method throws following Exceptions: 
 

Below programs demonstrate the forName() method.
Example 1:
 






// Java program to demonstrate forName() method
 
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
 
        // returns the Class object for this class
        Class myClass = Class.forName("Test");
 
        ClassLoader loader = myClass.getClassLoader();
 
        // get the Class instance using forName method
        Class c1
            = Class.forName("java.lang.String",
                            true,
                            loader);
 
        System.out.print("Class represented by c1: "
                         + c1.toString());
    }
}

Output: 
Class represented by c1: class java.lang.String

 

Example 2:
 




// Java program to demonstrate forName() method
 
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
 
        // returns the Class object for this class
        Class myClass = Class.forName("Test");
 
        ClassLoader loader = myClass.getClassLoader();
 
        // get the Class instance using forName method
        Class c1
            = Class.forName("java.lang.Integer",
                            false,
                            loader);
 
        System.out.print("Class represented by c1: "
                         + c1.toString());
    }
}

Output: 
Class represented by c1: class java.lang.Integer

 

Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#forName-java.lang.String-boolean-java.lang.ClassLoader-
 


Article Tags :