Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a class exists

Tags:

java

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?

like image 826
Brendon McCullum Avatar asked Nov 18 '15 07:11

Brendon McCullum


People also ask

Which function is used to check if class is exist or not?

The class_exists() function in PHP checks if the class has been defined. It returns TRUE if class is a defined class, else it returns FALSE.

How do you check if a HTML element has a class?

To check if the element contains a specific class name, we can use the contains method of the classList object.


1 Answers

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.

like image 174
Steve Chaloner Avatar answered Oct 12 '22 07:10

Steve Chaloner