6

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?

OddDev
  • 3,644
  • 5
  • 30
  • 53

2 Answers2

11

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.

Steve Chaloner
  • 8,162
  • 1
  • 22
  • 38
6

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

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

}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 2
    However, keep in mind that this actually loads the class, which may have side effects. Also, it can fail if the class itself exists, but can not load due to missing classes it relies on. – Thomas Stets Nov 18 '15 at 07:10