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 5203 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.

Leave a Comment


x

You might be Interested in these Posts

Video - Angular Router - Brian Ford

Video - Angular Router - Brian Ford http://www.youtube.com/watch?v=sfV0ApyN5fM ...

Video - An Angular2 Todo App: First look at App Development in Angular2

In this screencast , David East , one of the core contributor of the Angular provides a glimpse of A...

Video - Getting started with Angular 2

In this screencast , Alex Eagle , developer on the Angular team talks about Angular 2 developer prev...