John Goering
John Goering

Reputation: 39030

Check if class exists in Java classpath without running its static initializer?

If I use

   try {
      Class.forName("my.package.Foo");
      // it exists on the classpath
   } catch(ClassNotFoundException e) {
      // it does not exist on the classpath
   }

the static initializer block of "Foo" is kicked off. Is there a way to determine whether a class "my.package.Foo" is on the classpath without kicking off its static initializer?

Upvotes: 72

Views: 34424

Answers (2)

dStulle
dStulle

Reputation: 667

Since Java 9 there is a new Method that checks if the class exists but without throwing an exception in case the class does not exist this should be prefered instead of an expected exception.

For example this function checks the existence of a class when given the package and class name:

/**
 * Checks if a class can be found with the classloader.
 * @param moduleName a Module.
 * @param className the binary name of the class in question.
 * @return true if the class can be found, otherwise false.
 */
private boolean classExists(String moduleName, String className) {
    Optional<Module> module = ModuleLayer.boot().findModule(moduleName);
    if(module.isPresent()) {
        return Class.forName(module.get(), className) != null;
    }
    return false;
}

Bonus: Additional function that does only take one parameter

/**
 * Checks if a class can be found with the classloader.
 * @param name the fully qualified name of the class in question.
 * @return true if the class can be found, otherwise false.
 */
private boolean classExists(String name) {
    int lastDot = name.lastIndexOf('.');
    String moduleName = name.substring(0, lastDot);
    String className = name.substring(lastDot+1);
    return classExists(moduleName, className);
}

Link: related JavaDoc

Upvotes: 1

Andr&#233;
Andr&#233;

Reputation: 2353

Try the forName(String name, boolean initialize, ClassLoader loader) method of Class and set the param initialize to false.

JavaDoc link

Upvotes: 94

Related Questions