Reprint Please specify : Http://blog.csdn.net/uniquewonderq
First differentiate what is dynamic loading and what is static loading?
Class.forName ("Full name of the class");//The Third way of expressing class types
Not only represents the class type of the class, but also represents the dynamic load class
To differentiate between compilation and run.
The load class at compile time is a static load class. The runtime load class is a dynamic load class.
At compile time you need to load all the classes that you might use.
The demo code is as follows: A functional class, preferably using dynamic loading. such as, update, upgrade, add new features and so on.
The first is an interface for dynamic loading. You can experience it after a while.
Package Com.test;interface officeable {public void Start ();}
Next, define a word and Excel to implement this interface separately
Package com.test; Class Word implements officeable{ @Override public void Start () { System.out.println ("Word: Start ");} }
Package com.test;/** * * @author WONDERQ */public class Excel implements officeable{ @Override public void Start () { System.out.println ("Word: Start ");} }
The following is the Officebetter class for testing
Package Com.test;public class Officebetter {public static void Main (string[] args) { String classname= "com.test . word "; System.out.println ("classname=" +classname); try { //Dynamic load class, at run time, compile time without error class C=class.forname (className); The type of the class is created by the class type officeable oa= (officeable) c.newinstance ();//Parent class variable OA points to subclass object Oa.start (); } catch ( Exception e) { e.printstacktrace ();}} }
Instead of compiling the static load class, you can load the class dynamically each time you run the class. Reduces the overhead of the system. Of course, this program can be written in a method, and then the parameters to write the name of the class can be encapsulated as a separate module.
Run the result of this class:
Run
Classname=com.test.word
Word.. Start
Java--reflect (reflection) Special topic 2--Dynamic Load Class