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?
Asked
Active
Viewed 1,284 times
6
-
2I do not understand why you get down voted its a valid question by my opinion. Welcome to SO! – HRgiger Nov 18 '15 at 07:10
-
1@HRgiger: Thank you, appreciate. :) – Brendon McCullum Nov 18 '15 at 07:13
-
I can understand the downvote. a) The question is poorly worded. b) It is not well researched. c) see below – Markus W Mahlberg Nov 18 '15 at 07:50
-
Possible duplicate of [Getting class by its name](http://stackoverflow.com/questions/10119956/getting-class-by-its-name) – Markus W Mahlberg Nov 18 '15 at 07:50
2 Answers
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
-
2However, 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