Java反射之靜態加載和動態加載舉例小記

靜態加載:spa

package com.imooc.加載類;

public class Office_Static {
	public static void main(String[] args) {
		//new 建立對象,是靜態加載類,在編譯時刻就須要加載全部的可能使用到的類
		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也要加載


動態加載:excel

            一、接口OfficeAble :code

package com.imooc.加載類;

public interface OfficeAble {
	public void start();
}
            二、Word實現接口:

package com.imooc.加載類;

public class Word implements OfficeAble{
	public void start(){
		System.out.println("word start");
	}

}
               三、Excel實現接口:


package com.imooc.加載類;

public class Excel implements OfficeAble{

	public void start(){
		System.out.println("excel start");
	}
}

               四、Main方法

package com.imooc.加載類;

public class OfficeBetter {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			//動態加載類,在運行時刻加載
			Class c = Class.forName(args[0]);//在運行配置裏面輸入com.imooc.加載類.Excel
			//經過類類型,建立該類對象(先轉換爲Word和Excel的共同接口OfficeAble)
			OfficeAble oa = (OfficeAble)c.newInstance();
			oa.start();
			
			//不推薦下面兩種,由於不肯定是加載Word仍是Excel,要強轉
//			Word word = (Word)c.newInstance();
//			word.start();
//			Excel excel = (Excel)c.newInstance();
//			excel.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
相關文章
相關標籤/搜索