首页 > 代码库 > Cedar老师的java中的反射学习笔记(二)--动态加载

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.javaoffice.java:5: error: cannot find symbol        Word w=new Word();        ^  symbol:   class Word  location: class Officeoffice.java:5: error: cannot find symbol        Word w=new Word();                   ^  symbol:   class Word  location: class Officeoffice.java:8: error: cannot find symbol        Excel e=new Excel();        ^  symbol:   class Excel  location: class Officeoffice.java:8: error: cannot find symbol        Excel e=new Excel();                    ^  symbol:   class Excel  location: class Office4 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.javaC:\Users\SheroHuo\Desktop\test>javac Office.javaOffice.java:8: error: cannot find symbol        Excel e=new Excel();        ^  symbol:   class Excel  location: class OfficeOffice.java:8: error: cannot find symbol        Excel e=new Excel();                    ^  symbol:   class Excel  location: class Office2 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.javaC:\Users\SheroHuo\Desktop\test>java OfficeNew Wordword....start

  

 

Cedar老师的java中的反射学习笔记(二)--动态加载