Java How to – Find if the Class exists or not

Published on February 18, 2016 by abundantcode

Filed under Java

Last modified February 17, 2016

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 0 (0 votes)

This article have been viewed 2789 times

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.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment


x

You might be Interested in these Posts

C Program to display Inverted half-pyramid using *

Problem Write a program in C to print Inverted half-pyramid using * as shown below.The program shou...

How to use array Rank in C# ?

In C# , the Rank property of the array is is used to get the rank of the array. In simple terms , ra...

How to append an array to another in JavaScript ?

In JavaScript , you may want to append one array to another array(s) to combine their elements resul...