Friday, September 5, 2025
HomeLanguagesJavaClass forName() method in Java with Examples

Class forName() method in Java with Examples

The forName() method of java.lang.Class class is used to get the instance of this Class with the specified class name. This class name is specified as the string parameter.
Syntax: 
 

public static Class<T> forName(String className) throws ClassNotFoundException

Parameter: This method accepts the parameter className which is the Class for which its instance is required.
Return Value: This method returns the instance of this Class with the specified class name.
Exception: This method throws following Exceptions: 
 

  • LinkageError: if the linkage fails
  • ExceptionInInitializerError: if the initialization provoked by this method fails
  • ClassNotFoundException: if the class cannot be located

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

Java




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


Output: 

Class represented by c1: class java.lang.String

 

Example 2:
 

Java




// Java program to demonstrate forName() method
 
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        // get the Class instance using forName method
        Class c1 = Class.forName("java.lang.Integer");
 
        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-
 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS