静态加载:
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也要加载
动态加载:
1、接口OfficeAble :
package com.imooc.加载类; public interface OfficeAble { public void start(); }
2、Word实现接口:
package com.imooc.加载类; public class Word implements OfficeAble{ public void start(){ System.out.println("word start"); } }
3、Excel实现接口:
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 { //动态加载类,在运行时刻加载 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(); } } }
时间: 2024-11-07 10:08:25