靜態(tài)加載:
package com.imooc.加載類;public class Office_Static { public static void main(String[] args) { //new 創(chuàng)建對象,是靜態(tài)加載類,在編譯時刻就需要加載所有的可能使用到的類 if("Word".equals(args[0])){ Word w = new Word(); w.start(); } if("Excel".equals(args[0])){ Excel e = new Excel(); e.start(); } }}這個程序編譯時必須有Word和Excel這兩個類存在才行,即使判斷后用不到Excel也要加載
動態(tài)加載:
1、接口OfficeAble :
package com.imooc.加載類;public interface OfficeAble { public void start();}2、Word實現(xiàn)接口:
package com.imooc.加載類;public class Word implements OfficeAble{ public void start(){ System.out.println("word start"); }}3、Excel實現(xiàn)接口:
package com.imooc.加載類;public class Excel implements OfficeAble{ public void start(){ System.out.println("excel start"); }}4、Main方法
package com.imooc.加載類;public class OfficeBetter { /** * @param args */ public static void main(String[] args) { try { //動態(tài)加載類,在運行時刻加載 Class c = Class.forName(args[0]);//在運行配置里面輸入com.imooc.加載類.Excel //通過類類型,創(chuàng)建該類對象(先轉(zhuǎn)換為Word和Excel的共同接口OfficeAble) OfficeAble oa = (OfficeAble)c.newInstance(); oa.start(); //不推薦下面兩種,因為不確定是加載Word還是Excel,要強轉(zhuǎn)// Word word = (Word)c.newInstance();// word.start();// Excel excel = (Excel)c.newInstance();// excel.start(); } catch (Exception e) { e.printStackTrace(); } }}以上就是小編為大家?guī)淼腏ava反射之靜態(tài)加載和動態(tài)加載的簡單實例的全部內(nèi)容了,希望對大家有所幫助,多多支持武林網(wǎng)~
新聞熱點
疑難解答