0

I have a simple question about the java classloading mechanism.

I think that the default class loader loads user-defined classes. If I specify other jars in the classpath, does the default classloader go through each jar and load classes from each jar at application startup?

user826323
  • 2,248
  • 6
  • 43
  • 70
  • possible duplicate: http://stackoverflow.com/questions/6266156/does-system-classloader-load-all-classes-in-classpath-even-if-theyre-not-actuall – stivlo Oct 07 '11 at 15:40
  • I have about 250 jars in my project. If it was loading all classes from all jar at startup it would make me cry. – MarianP Oct 07 '11 at 16:16

1 Answers1

1

No, it loads classes whenever they are first referenced, either through Class.forName() or through direct use in your code.

Example:

public class First {
    static {
        System.out.println("first");
    }
    public static void main(final String[] args) {
        System.out.println("second");
        Second.third();
    }
}
public class Second {
    static {
        System.out.println("third");
    }
    public static void third() {
        System.out.println("fourth");
    }
}

If you run First as a main class, the output is:

first   <-- First is loaded
second  <-- method in First is executed
third   <-- Second is loaded
fourth  <-- Method in Second is executed
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • Let's say that there are 10 jars defined in the classpath. And if I need Test object which is defined in 7th jar in the classpath at runtime, does it start looking for it from the 1st jar? – user826323 Oct 07 '11 at 15:42
  • @user826323 yes, it searches the classpath elements (jars or folders) in the order they appear in your classpath – Sean Patrick Floyd Oct 07 '11 at 15:46