The third method we talked about in the first lesson
Class.forName ("Full name of the class");
Not only represents the class type of the class, it also represents the dynamic load class
Please distinguish compile, run
Compile time load class is static load class, runtime load class is dynamic load class
Now the development tools such as Eclipse to hide the compilation process
Here's an experiment.
For example, write the following Office.java file in Notepad
Class Office {public static void main (string[] args) {if (("word"). Equals (Args[0])) {Word w = new Word (); W.start ();} if (("Excel"). Equals (Args[0])) {Excel e = new Excel (); E.start ();}}}
Will error
Because the new creation object is a static load class, all of the possible classes are loaded at compile time
Now we create the world class
At this point the compiler Exel class was not found (because I only created the world without creating an Excel Class).
But what's wrong with that???
If we only want to use the Word feature, the Word feature that does not have an Excel class program is not too good to use. If Office has 100 features, there is a problem with a function, the other 99 features are not used so is not very good!!!!
Because the new creation object is a static load class, all of the possible classes are loaded at compile time
if we want to implement that class before we load that class. Do not load when it is useless. How is it implemented? ( which part of the function to load the corresponding code, no use will not load, so even if a function is problematic, the other 99 functions can still be used )
This is actually the dynamic load class.
How do I load classes dynamically?
Optimization program:
public class Officebetter {public static void main (string[] args) {try {//Dynamically load class, load Class C = Class.forName (Args[0] at run time);// Create object//Create object of this class through class type officeable OA = (officeable) c.newinstance (); Oa.start ();} catch (Exception e) {e.printstacktrace ();}}}
Officeable is a standard that allows Word and Excel to implement this interface
Interface Officeable {public void Start ();}
This compiles without any problems
If I want to use Word function, just let world implement officeable interface.
<pre name= "code" class= "java" style= "font-size:10px;" >class Word implements officeable {@Overridepublic void start () {//TODO auto-generated method StubSystem.out.println ( "Word start");}}
If you want to add a new feature, just implement the Officeable interface, the original code does not need to change
General functional classes use dynamic loading
such as QQ online upgrade, the original code does not change only need to add new features on the line
Java reflection Lesson two dynamic load classes