2011-10-07 51 views
0

我有一个关于java类加载机制的简单问题。java classloading classpath

我认为默认的类加载器加载用户定义的类。如果我在类路径中指定了其他jar,默认的classloader会在应用程序启动时通过每个jar并从每个jar中加载类吗?

+0

可能重复:http://stackoverflow.com/questions/6266156/does-system -classloader-load-all-class-class-class-even-if-theyre-not-actuall – stivlo

+0

我的项目中有大约250个罐子。如果它在启动时从所有jar中加载所有类,它会让我哭泣。 – MarianP

回答

1

不,它通过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 
+0

假设在类路径中定义了10个罐子。如果我需要在运行时在类路径的第7个jar中定义的Test对象,它是否从第一个jar开始寻找它? – user826323

+0

@ user826323是的,它按照它们出现在类路径中的顺序搜索类路径元素(罐子或文件夹) –