How to check if a Class Exists in Java
1). Using Class.forName()
In this way, we are using the reflection for the class existence check.
It will throw ClassNotFoundException if the class not found.
try {
Class yourClass = Class.forName("classname");
Object object = yourClass.newInstance();
} catch(ClassNotFoundException e) {
//Throw error or whatever
}
2). Check If Class Exists in the given path
We can create a file giving that path and check whether that file exists or not.
File classFile = new File("path/YourClass.class");
if (fileTest.exists()) {
System.out.println("exists");
//Instantiate the class.
} else {
System.out.println("not exists");
}
In this article, we have seen How to check if a Class Exists in Java.
0 Comments
Post a Comment