Class.forName ("Full name of the class")
1) not only represents the class type of the class, but also represents the dynamic load class
2) Please distinguish compile, run
3) Compile time load class is static load class, run time load class is dynamic load class
such as the following:
For example, a class has the following method, when the condition satisfies word, call word w=new word ();
When Excel is satisfied, call Excel e=new Excel ();
This method of using new to create an object belongs to the static load class, compile time will need to load all possible classes, once Word or Excel does not exist, compile the time will be error, pass.
If I want to use which class, load which class, only use the time, only to load, then can solve this problem.
The problem can be furnished by dynamically loading the class.
The specific implementation is as follows:
Package Com.reflect; Public class Officebetter { publicstaticvoidthrows Exception { Class C1=class.forname ("Com.reflect.Word"); officeable OA=(officeable) c1.newinstance (); by instantiating a total object through Newinstance (), in order for the different classes to be able to convert, you need to define a total interface for these classes Oa.start ();} }
Instantiate this class of objects through the Newinstance method, but if the word class needs to be converted to word, if it is an Excel class, it needs to be converted to an Excel class,
For convenience, it is possible to define altogether a common interface for these several classes, officeable. The required class implements its interface.
Package Com.reflect; Public Interface officeable { publicvoid start ();}
Word implements an interface
Package Com.reflect; Public class Implements officeable { @Override publicvoid start () { System.out.println ("word...is created");} }
What kind of class is needed, just in this way.
Java Reflection--dynamic loading