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?

2
  • possible duplicate: stackoverflow.com/questions/6266156/… Commented Oct 7, 2011 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. Commented Oct 7, 2011 at 16:16

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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 yes, it searches the classpath elements (jars or folders) in the order they appear in your classpath

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.