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?
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.
To check if the element contains a specific class name, we can use the contains method of the classList object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With