我有一个关于java类加载机制的简单问题。
我认为默认类加载器加载用户定义的类。如果我在类路径中指定其他 jar,默认类加载器是否会在应用程序启动时遍历每个 jar 并从每个 jar 加载类?
最佳答案
不,它会在首次引用类时加载类,无论是通过 Class.forName()
或者直接在代码中使用。
示例:
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");
}
}
如果你运行First
作为主类,输出为:
first <-- First is loaded
second <-- method in First is executed
third <-- Second is loaded
fourth <-- Method in Second is executed
关于使用类路径进行 java 类加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7689514/