反射學習(二)java動態載入類
阿新 • • 發佈:2019-02-14
一 什麼是動態載入類 什麼是靜態載入類
Class.forName 不僅表示類的類型別,還代表了動態載入類。編譯時載入是靜態載入類,
執行時載入是動態載入類。
請大家區分編譯 執行。
二.為何要使用動態載入類
用記事本寫了一個程式 並沒有寫A類和B類以及start方法
public class office { public static void main(String[] args) { if ("word".equals(args[0])) { word w = new word(); w.start(); } if ("excel".equals(args[0])) { excel e = new excel(); e.start(); } } }
在執行javac office.java時會報錯,原因是word和excel類不存在。假設我們想要使用word功能,寫了一個word類,但是由於excel的原因,word功能也不能使用。
我們會發現,我們並不一定用到word功能或excel功能,可是編譯卻不能通過。而在日常的專案中,如果我們寫了100個功能,因為一個功能的原因而導致所有功能不能使用,明顯使我們不希望的。在這裡,為什麼會在編譯時報錯呢?new 是靜態載入類,在編譯時刻就需要載入所有可能使用到的功能。所以會報錯。而在日常中我們希望用到哪個就載入哪個,不用不載入,就需要動態載入類。
使用動態載入類時,我們不用定義100種功能,只需要通過實現某種標準(實現某個介面)。
程式碼:
public interface officeInterface {
public void start();
}
public class word implements officeInterface{
@Override
public void start() {
System.out.println("word...start...");
}
}
public class excel implements officeInterface{ @Override public void start() { System.out.println("excel...start..."); } }
public class office{
public static void main(String args[]){
try{
Class c=Class.forName(args[0]);
officeInterface oi = (officeInterface) c.newInstance();
oi.start();
}catch(Exception e){
e.printStackTrace();
}
}
}
這樣的話,office類不需要再重新編譯。新加功能的話只需要再寫一個類實現officeInterface介面,例如PPT類,到時候只需要把PPT類重新編譯一下,直接呼叫office類就可以實現特定的功能。這就是所謂的動態載入類。