Sunday 6 March 2022

Java: Check whether a class exists in the classpath or not

By loading the class, we can check whether the class exists in the class path or not. Below snippet checks whether a class is available in the class path or not.

 

 


Find the below working application.

 

ClassAvailableCheck.java

package com.sample.app.reflections;

public class ClassAvailableCheck {
	
	public static boolean isClassAvailable(String classQualifiedName) {
        ClassLoader classLoader = ClassAvailableCheck.class.getClassLoader();
        try {
            Class<?> laodedClazz = classLoader.loadClass(classQualifiedName);
            return (laodedClazz != null);
        } catch (ClassNotFoundException e) {
        	e.printStackTrace();
            return false;
        }
    }

	public static void main(String[] args) {
		System.out.println("is java.lang.System available: " + isClassAvailable("java.lang.System"));
		System.out.println("is org.json.JsonUtil available : " + isClassAvailable("org.json.JsonUtil"));
	}

}

Sample Output

is java.lang.System available: true
java.lang.ClassNotFoundException: org.json.JsonUtil
    at java.net.URLClassLoader.findClass(URLClassLoader.java:387)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at com.sample.app.reflections.ClassAvailableCheck.isClassAvailable(ClassAvailableCheck.java:8)
    at com.sample.app.reflections.ClassAvailableCheck.main(ClassAvailableCheck.java:18)
is org.json.JsonUtil available : false

 



You may like

Interview Questions

How to check whether string contain only whitespaces or not?

How to call base class method from subclass overriding method?

Can an interface extend multiple interfaces in Java?

instanceof operator behavior with interface and class

Call the main method of one class from other class using reflection

No comments:

Post a Comment