One: Define
The Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the object's methods are called the reflection mechanisms of the Java language.
II: Usage Scenarios
Generally used in the framework of the package. Hibernate and struts are implemented by reflection mechanisms.
Example: Database driver Class.forName ("Com.mysql.jdbc.Driver") loaded in JDBC;
Three: Advantages
The advantage of the reflection mechanism is that it can achieve dynamic creation of objects and compile, which shows great flexibility.
If we had two programmers, a programmer would need to use the class written by the second programmer while writing the program, but the second programmer did not complete the class he wrote. So can the first programmer's code be compiled? This is not possible by compiling. Using the mechanism of Java reflection, the first programmer can compile the code without getting the class that the second programmer wrote.
four: Common methods
how to get a constructor function
Constructor GetConstructor (class[] params)//obtained according to specified parametersPublic Constructor
Constructor getdeclaredconstructor (class[] params)//obtained according to specified parametersPublic and non-public constructors
methods of obtaining class methods
Method GetMethod (String name, class[] params), obtained by method name, parameter type
Method Getdeclaredmethod (String name, class[] params)//Get public and non-public methods based on method name and parameter type
methods for obtaining properties in a class
Field GetField (String name)//Get the appropriate public variable based on the variable name
Field Getdeclaredfield (String name)//Get public and non-public variables by method name
Five: code example
test1 Execution Results:
test2 Execution Results
Java Fundamentals: Reflection mechanism