1. 程式人生 > >java 載入類的三種方法

java 載入類的三種方法

載入類的幾種方法

所有資源都通過ClassLoader載入到JVM裡,那麼在載入資源時當然可以使用ClassLoader,只是對於不同的資源還可以使用一些別的方式載入,例如對於類可以直接new,對於檔案可以直接做IO等。

載入類的幾種方法假設有類A和類B,A在方法amethod裡需要例項化B,可能的方法有3種。對於載入類的情況,使用者需要知道B類的完整名字(包括包名,例如"com.rain.B")  
1. 使用Class靜態方法 Class.forName  

    Class cls = Class.forName("com.rain.B"); 
    B b = (B)cls.newInstance(); 



2. 使用ClassLoader  
    /* Step 1. Get ClassLoader */ 
    ClassLoader cl; // 如何獲得ClassLoader參考本文最後

    /* Step 2. Load the class */ 
    Class cls = cl.loadClass("com.rain.B"); // 使用第一步得到的ClassLoader來載入B 

    /* Step 3. new instance */ 
    B b = (B)cls.newInstance(); // 有B的類得到一個B的例項 

3. 直接new  
    B b = new B(); 

ps:

獲得ClassLoader的幾種方法可以通過如下3種方法得到ClassLoader  
this.getClass.getClassLoader(); // 使用當前類的ClassLoader  
Thread.currentThread().getContextClassLoader(); // 使用當前執行緒的ClassLoader  
ClassLoader.getSystemClassLoader(); // 使用系統ClassLoader,即系統的入口點所使用的ClassLoader。