Cedar老师的java中的反射学习笔记(二)--动态加载
静态加载:
编译时刻加载类
(1)new创建对象是静态加载类,在编译时加载类
动态加载:
运行时刻加载类
(2)Class c=Class.forName() 动态加载类
c.newInstance();
代码:
(1)创建一个office类:
class Office { public static void main(String[] args) { Word w=new Word(); w.start(); Excel e=new Excel(); e.start(); } }
编译后报错:
C:\Users\SheroHuo\Desktop\test>javac office.java office.java:5: error: cannot find symbol Word w=new Word(); ^ symbol: class Word location: class Office office.java:5: error: cannot find symbol Word w=new Word(); ^ symbol: class Word location: class Office office.java:8: error: cannot find symbol Excel e=new Excel(); ^ symbol: class Excel location: class Office office.java:8: error: cannot find symbol Excel e=new Excel(); ^ symbol: class Excel location: class Office 4 errors
new创建对象是静态加载类,在编译时加载类,因为没有word和excel类。
(2)创建word类:
class Word { public void start(){ System.out.println("word....start"); } }
编译word 在编译office
编译结果:
C:\Users\SheroHuo\Desktop\test>javac Word.java C:\Users\SheroHuo\Desktop\test>javac Office.java Office.java:8: error: cannot find symbol Excel e=new Excel(); ^ symbol: class Excel location: class Office Office.java:8: error: cannot find symbol Excel e=new Excel(); ^ symbol: class Excel location: class Office 2 errors
有时候word或excel可能不会用到,希望采用动态加载:
创建一个新的OfficeNew类,通过类类型创建对象。
class OfficeNew { public static void main(String[] args) { try{ Class c=Class.forName(args[0]); OfficeAll oa=(OfficeAll)c.newInstance(); //通过类类型创建对象 oa.start(); }catch(Exception e){ e.printStackTrace(); } } }
创建一个标准-接口:OfficeAll,使word excel实现这个接口:
interface OfficeAll { public void start(); }
class Word implements OfficeAll { public void start(){ System.out.println("word....start"); } }
分别编译word,OfficeNew,再运行word方法:
C:\Users\SheroHuo\Desktop\test>javac Word.java
C:\Users\SheroHuo\Desktop\test>javac OfficeNew.java C:\Users\SheroHuo\Desktop\test>java OfficeNew Word word....start
勇气,信念,坚持