In the design model, reflection is used in many places. In particular, read information from the configuration file and use this information for dynamic loading. Reflection is particularly common. Here we will discuss reflection and related concepts again.
Classloader class loading mechanism:
L classes in Java are not loaded into memory at one time
L It is dynamically loaded to the memory as needed, that is, the dynamic loading during the running.
L static statements are executed once after loading and once
L dynamic statement block is executed every time a new object is created.
There are many classloader in Java:
Bootstrap Class Loader top-level Cl, responsible for class management. It may be written in C or assembly. User Access is not allowed.
Extension Class Loader
Application Class Loader
Other class loaders
N secure Class Loader
N url clas Loader
It seems that the class name is still read in the configuration file. Reflection is the most common.
1. Location of the property file:
Do not die in a directory.
Do not use relative paths (consider the case where it is placed in the jar package)
The most common location, put in classpath. You can be accessed by properties. It is embodied in the src directory in eclipse. The SRC compiled items will be put into the classpath of the current project by ECLIPSE, so they can be accessed by properties.
2. Attribute file content:
Observers =Com. bjsxt. DP. Observer. Dad, Com. bjsxt. DP. Observer. Grandfather, Com. bjsxt. DP. Observer. Dog
ObserversIs the key.
Com. bjsxt. DP. Observer. Dad, Com. bjsxt. DP. Observer. Grandfather, Com. bjsxt. DP. Observer. DogIs the value, separated by commas.
3.Among the usersPropertymgrTo obtain information in the configuration file.
ClassPropertymgr {
//Use System objects,Properties, Requires that the configuration file be placed inClasspathInside
PrivateStaticPropertiesProps
=NewProperties ();
Static{
Try{
//PassPropertiesFind the configuration file
//Note:Try catch.
Props. Load (test.Class. Getclassloader (). getresourceasstream ("Com/bjsxt/DP/Observer/observer. properties"));
}Catch(Ioexception e ){
E. printstacktrace ();
}
}
//PassGetpropertyTo obtain the attribute value. Is in the configuration file, the following part
PublicStaticStringGetproperty(String key ){
ReturnProps. Getproperty (key );
}
}
In fact, the obtained attribute value is not complete yet, and the result is a string. You must continue to use the string split method to obtain each class. Then generate the objects of these classes.
//PairPropertiesThe obtained string, usingSplitTo process
String [] Observers = propertymgr.Getproperty("Observers"). Split (",");
//An object is generated for each class.Try catch
For(String S: Observers ){
Try{
C. addwakenuplistener (wakenuplistener) (class.Forname(S). newinstance ()));
}Catch(Instantiationexception e ){
E. printstacktrace ();
}Catch(Illegalaccessexception e ){
E. printstacktrace ();
}Catch(Classnotfoundexception e ){
E. printstacktrace ();
}
}