2

On compile or run, we usually have a lot of class/jar dependencies, and the database driver's jar is just one of them. So, does

Class.forName(X)

have to scan all these .class/.jar file names to locate proper driver class named X? If not, does Class.forName has any rule/algorithm to find particular class?

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Hind Forsum
  • 9,717
  • 13
  • 63
  • 119
  • 2
    It will look for the class through all folders/archives on the classpath. Why thequestion? BTW, it still looks for classes in the same places even when it encounters class references by executing code normally. – ernest_k Dec 01 '18 at 13:01
  • Check this : https://community.softwaregrp.com/t5/Fortify-User-Discussions/How-to-include-jar-files-in-a-scan-project/td-p/1546330 and https://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection – Mohammadreza Khatami Dec 01 '18 at 13:17

1 Answers1

1

It delegates to the ClassLoader of the calling class. In most cases the answer is yes but there are ClassLoader implementations with more sophisticated rules e.g. OSGI which uses dynamic modules or JEE Server Application Classloading.

public static Class<?> forName(String className) throws ClassNotFoundException {
  Class<?> caller = Reflection.getCallerClass();
  return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111