Brendon McCullum
Brendon McCullum

Reputation: 183

How to check whether a class exists

Is there any static method of the 'Class' class that can tell us whether a user entered class (in the form of a String) is a valid existing Java class name or not?

Upvotes: 6

Views: 1479

Answers (2)

Steve Chaloner
Steve Chaloner

Reputation: 8202

You can use Class.forName with a few extra parameters to get around the restrictions in Rahul's answer.

Class.forName(String) does indeed load and initialize the class, but Class.forName(String, boolean, ClassLoader) does not initialize it if that second parameter is false.

If you have a class like this:

public class Foo {
    static {
        System.out.println("foo loaded and initialized");
    }
}

and you have

Class.forName("com.example.Foo")

the output in the console will be foo loaded and initialized.

If you use

Class.forName("com.example.Foo", 
              false, 
              ClassLoader.getSystemClassLoader());

you will see the static initializer is not called.

Upvotes: 12

Rahul Tripathi
Rahul Tripathi

Reputation: 172408

You can check the existence of a class using Class.forName like this:

try 
{
   Class.forName( "myClassName" );
} 
catch( ClassNotFoundException e ) 
{

}

Upvotes: 6

Related Questions