Java How to – Find if the Class exists or not

Problem Statement

You need to test for the presence of a class from your java program.

Solution

Use Class.forName method to find if a particular class exists. Below is a sample code snippet demonstrating the usage of Class.forName to find out if the class “test” exists. Note that this method throws an exception incase the class cannot be loaded.

public class Main {

public static void main(String[] args) {

    try
    
    {
    
        Class.forName("test");
        
        System.out.println("Class found");
    
    }
    
    catch(Exception ex)
    
    {
    
        System.out.println("Class not found");
    
    }
    
}

}

Note: You need to pass the complete class name including the package name to test for the presence of the class.