How to check if a class exists

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

+6
source share
2 answers

You can verify the existence of a class using Class.forName as follows:

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

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

Class.forName(String) does load and initialize the class, but Class.forName(String, boolean, ClassLoader) does not initialize it if this 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") 

console output will be foo loaded and initialized .

If you use

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

you will see that the static initializer is not being called.

+9
source

All Articles