Java reflection Issue 1. Use class = Class. forname ("net. smarthing. www. userdao"); // class pack path
2. Obtain the Method
Method [] Methods = Class. getdeclaredmethods ();
3. Obtain the field
Field [] fielsd = Class. getdeclaredfields []; // get all fields
Field fields = Ca. getdeclaredfield ("username"); // get one of Field
4. Execute reflection Functions
Method method = methods [I] // get one of method from all the method;
Object OBJ = Class. newinstance ();
Method. Invoke (OBJ, paramarray); // paramarray is array that include all paramether need; example:
/**
*
* @ Author sonic
* @ Throws exception
* @ Throws RemoteException
*/
Public object invokeroledaomethod (string methodname, string parameter) throws exception {
Class roclass = Class. forname ("net. smarthing. www. roledao ");
Method [] Methods = roclass. getdeclaredmethods ();
Class rettype = NULL; // return parameter type
/**
* Parameter for Method
* If the method's parameter is Boolean typt so need to change like that object [] AA = {new Boolean (parameter )};
*/
Object [] methodarray = {parameter };
Object returnobj = NULL; // return object
For (INT I = 0; I <methods. length; I ++ ){
Method me = methods [I];
If (methodname. Equals (Me. getname ())){
Rettype = me. getreturntype ();
Object OBJ = roclass. newinstance ();
Returnobj = me. Invoke (OBJ, methodarray); // return the object which same to method.
}
}
Return returnobj;
} The Java class loading mechanism is recommended.
Java is a dynamic interpreted programming language. When a specified program runs, the Java Virtual Machine will compile and generate the program. class files are loaded into the memory according to requirements and certain rules, and organized into a complete Java application. The Java language compiles each separate class and interface implements into a separate. Class file. These files are dynamic loaded units for the Java Runtime Environment. Because of this feature of Java, We can compile only the units to be modified without re-compiling other code and compile the modified files. the class file is placed in the Java path. When the Java Virtual Machine is re-activated next time, the logic-based Java application will load the new modified. class file, and its own functions have also been updated, which is the dynamic nature of Java. The following uses a simple example to give you a basic understanding of Java's dynamic loading: Class testclassa {public void method () {system. out. println ("loading classa") ;}} public class classloadertest {public static void main (string ARGs []) {testclassa = new testclassa (); testclassa. method () ;}} after compilation, enter the command: Java-verbose: Class classloadertest to execute the file. Output structure (1)
Figure (1) from the running results, we can see that JRE (javaruntime environment) First loads the classloadertest file and then loads the testclassa file, thus implementing dynamic loading. 1. in order to optimize the system and improve the program execution speed, at the beginning of JRE running, all the basic classes required for Java running are loaded into the memory using the pre-loading method, these units are often used during Java program running, including the RT of JRE. all. class file. After the java. EXE virtual machine starts running, it will find the JRE environment installed on the machine, and then hand over the control to the JRE. The JRE class loader will RT under the lib directory. the jar basic category file library is loaded into the memory. These files are required for Java program execution. Therefore, the system loads these files at the beginning to avoid multiple I/O operations in the future, this improves program execution efficiency. Figure (2) We can see that multiple basic classes are loaded, java. Lang. Object, java. Io. serializable, and so on. Figure (2) compared to pre-loading, we need to use the load-on-demand method when we need to use the classes defined by ourselves in the program ), it is re-loaded when the Java program needs to be used to reduce memory consumption, because the original design of the Java language is oriented to the embedded field. It is worth noting that when does JRE load classes into the internal environment as needed? When defining a class instance, such as testclassa, the value of testclassa is null, that is, it has not been initialized and has not called the testclassa constructor, JRE loads testclassa only after testclassa = new testclassa () is executed. 2. The loading methods of implicit loading and display loading Java are divided into implicit and explicit loading. The above example uses the implicit loading method. Implicit loading means that we use the new keyword in the program to define an instance variable. when JRE executes the New Keyword, it loads the corresponding instance class into the memory. Implicit loading is very common and widely used. The JRE system automatically loads data in the background, reducing the workload and increasing the system security and program readability. Compared with implicit loading, display loading is not frequently used. The so-called display loading means that some programmers write their own programs to load the required classes into the memory. Let's look at a program: Class testclass {public void method () {system. out. println ("testclass-method") ;}} public class cltest {public static void main (string ARGs []) {try {Class C = Class. forname ("testclass"); testclass object = (testclass) C. newinstance (); object. method ();} catch (exception e) {e. printstacktrace () ;}} we load the custom class testclass through the forname (string s) method of the class, and The newinstance () method initializes the instance. In fact, the class still has many functions. I will not elaborate on them here. If you are interested, refer to the JDK documentation. The forname () method of class has another form: Class forname (string S, Boolean flag, classloader). S indicates the name of the class to be loaded, flag indicates whether the static zone is initialized when the function is called to load the class, and classloader indicates the loader required to load the class. Forname (string S) is implemented by classloader by default. getcallerclassloader () calls the class loader, but this method is private and cannot be called. If we want to use class forname (string S, Boolean flag, classloader) to load the class, you must specify the Class Loader. You can use the following method to implement: Test test = new test (); // test class is a custom test class; classloader Cl = test. getclass (). getclassloader (); // get the class loader of test; Class C = Class. forname ("testclass", true, Cl); a loader is required for loading a class. Here we get the loader CL for loading the test class as the loading te. Stclass class loader to load. 3. Before the custom class loading mechanism, we used to call the system class loader to implement loading. In fact, we can define our own class loaders. Java provides the java.net. urlclassloader class. The following is an example: Try {URL url = new URL ("file:/D:/test/lib /"); urlclassloader urlcl = new urlclassloader (new URL [] {URL}); Class C = urlcl. loadclass ("testclassa"); testclassa object = (testclassa) C. newinstance (); object. method ();} catch (exception e) {e. printstacktrace ();} we use a custom class loader to load the testclassa class and call the method () method. Analyze this program: first, define the URL to specify where the Class Loader loads the class. The URL can point to any location on the Internet, you can also point to the file system (including jar files) in our computer ). In the above example, we will look for classes from file:/D:/test/lib/. Then we will define urlclassloader to load the required classes, and then we will use this instance. 4. after discussing the class loader's class system so much, let's take a closer look at the working principle of the Java Class Loader: When you execute Java ***. class, java.exe will help us find the JRE, and then find the JVM located inside the JRE. DLL, which is the real Java Virtual Machine. Finally, load the dynamic library and activate the Java Virtual Machine. After the virtual machine is activated, initialization will be performed first, such as reading system parameters. Once the initialization is complete, the bootstrap loader, the first class loader, is generated. bootstrap loader is written by C ++. In the initial work of this bootstrap loader, in addition to some basic initialization actions, the most important thing is to load launcher. in Java, and set its parent to null to indicate that its parent loader is bootstraploader. Then bootstrap loader needs to load the appclassloader in launcher. Java and set its parent to the previously generated extclassloader object. Both loaders exist in the form of static classes. It should be noted that launcher $ extclassloader. Class and launcher $ appclassloader. Class are both loaded by bootstrap loader, so there is no relationship between parent and which class loader is loaded. The following figure shows the relationship between the three elements: parent class
Parent class
Load
Load
Bootstraploader
Parent appclassloader
Parent extclassloader
These three loaders constitute our Java class loading system. They respectively look for the classes required by the program from the following paths: bootstraploader: Sun. boot. class. path extclassloader: Java. ext. dirs appclassloader: Java. class. the three system parameters of path can be passed through system. the getproperty () function obtains the corresponding path. You can view the specific path by programming. 5. to sum up and understand the class loading mechanism of Java, it plays a very important role for us to skillfully and flexibly use the Java language and improve the running efficiency of the program, in this way, the program quality can be improved as a whole.