Java reflection mechanism

Source: Internet
Author: User

Java reflection mechanism
I. What is the reflection mechanism?
In short, the reflection mechanism means that the program can obtain its own information during runtime. In java, if the class name is specified,
The reflection mechanism can be used to obtain all information about the class.
II. Where to use the reflection mechanism
Sometimes, we have used some knowledge, but we don't know what its terminology is. I used a line of code when I was just learning jdbc,
Class. forName (com. mysql. jdbc. Driver. class). newInstance (); but at that time, only the line of code is generated.
The driver object instance does not know its specific meaning. After listening to the reflection mechanism, I realized that this was reflection. Now there are a lot of open
The framework uses reflection mechanisms, while hibernate and struts use reflection mechanisms.
Iii. Advantages and disadvantages of the reflection mechanism
Why is reflection required? Simply creating an object involves Dynamic and Static concepts,
Static Compilation: determine the type during compilation, bind the object, that is, pass.
Dynamic Compilation: determines the type during runtime and binds the object. Dynamic compilation maximizes java flexibility and reflects many
To reduce the coupling between classes.
In a word, the advantage of the reflection mechanism is that it can dynamically create objects and compile objects, reflecting great flexibility, especially in the development of J2EE.
Its flexibility is very obvious. For example, a large software cannot be designed perfectly once.
After translation, it is released. When we find that some features need to be updated, we cannot ask the user to uninstall the previous feature and reinstall the new version. If
In this case, this software is certainly not used by many people. To use static data, you need to recompile the entire program once to implement the function.
But with the reflection mechanism, it does not need to be uninstalled. It only needs to be dynamically created and compiled at runtime, so that this function can be implemented.
Yes.
Its disadvantage is that it has an impact on performance. Reflection is basically an interpreted operation. We can tell JVM what we want to do and
Meet our requirements. This type of operation is always slower than simply performing the same operation.
4. What information can be obtained using the reflection mechanism?
In a word, if there is any information in the class, it can obtain any information, but the premise is to know the class name, or there will be no additional information
First, you must create a Class object based on the full name of the passed Class.
Class c = Class. forName (className); Note: className must be the full name, that is, including the package name, for example, cn. netjava. pojo. UserInfo;
Object obj = c. newInstance (); // create an Object instance
OK. If you have an object, everything is easy to do. If you want any information, there will be any information.
Methods for obtaining Constructors
Constructor getConstructor (Class [] params) // obtain the public Constructor Based on the specified parameter

Constructor [] getConstructors () // obtain all constructors of public

Constructor getDeclaredConstructor (Class [] params) // obtain the public and non-public constructors Based on the specified parameters.

Constructor [] getDeclaredConstructors () // obtain all public Constructors
Methods for obtaining class methods
Method getMethod (String name, Class [] params). Obtain the Method based on the Method name and parameter type.

Method [] getMethods () // obtain all public methods

Method getDeclaredMethod (String name, Class [] params) // obtain public and non-public methods based on the Method name and parameter type.

Method [] getDeclaredMethods () // obtain the public and non-public methods
Method for obtaining attributes in a class
Field getField (String name) // obtain the corresponding public Variable Based on the variable name

Field [] getFields () // obtain the public method in the class

Field getDeclaredField (String name) // obtain public and non-public variables based on the method name

Field [] getDeclaredFields () // obtain all public and non-public methods in the class
This is often the case. If you know this, everything else can be done well ......
5. What can I do with the reflection mechanism?
At the beginning, when using jdbc, I wrote to the students during database access. There are eight tables, each of which has an operation in addition, deletion, modification, and query.
At that time, I didn't know the concept of reflection mechanism, so I created different dao classes for different tables, not only at the development speed, but also in the code
The redundancy is so powerful that the most terrible thing is to look at it and then copy and modify it directly, because it is easy to make various low-level errors (case-insensitive, more
Or less than one letter ......), If an error occurs, you can find it for half a day.
With the java reflection mechanism, everything is easy to do. You only need to write a dao class, four methods, add, delete, modify, and query, and input different objects. That's OK,
There is no need to create a dao class for each table. The reflection mechanism will automatically help us with the rest, which is the benefit of this mechanism. To put it bluntly, the reflection mechanism is dedicated
This helps us with repetitive and rule-based tasks. Therefore, many software programs that automatically generate code now use the reflection mechanism, as long as you follow the rules
Input related parameters, so low-level programmers are slowly erased. Why? Because no code needs to be written, it can be developed by anyone.
What do sequencers do? So we have only one way out, that is, to work hard to become a Senior Programmer and to develop a fool's software to make other programmers cool ~
6. Use a reflection mechanism to add and query database data.
Basic principle: when saving data, extract all the attribute values of the objects to be saved and splice them together with SQL statements.
During the query, all the queried data is packaged into a java object.
Game Rules: As the saying goes, "No rule" is not a perfect match. Especially for programs, it can only do things with rules, but it cannot do things without rules ."
Preset rules
1) Each table object in the database has a pojo class, and each field in the table corresponds to an attribute in the pojo class.
In addition, the pojo class name is the same as the table name, the attribute name and field name are the same, and the case sensitivity is irrelevant, because the database is generally case insensitive.
2) add standard set and get methods for each attribute in the pojo class.
With the game rules, start the game.

1. First, there is a table in the database. Assume that the database name is blogsystem and the table name is userinfo.

2. Create the corresponding pojo class:

package cn.netjava.pojo; public class UserInfo {private int id;private String name;private String pwd;private int age; @Overridepublic String toString() {    return UserInfo [id= + id + , name= + name + , pwd= + pwd + , age=            + age + ];}public int getId() {    return id;}public void setId(int id) {    this.id = id;}public String getName() {    return name;}public void setName(String name) {    this.name = name;}public String getPwd() {    return pwd;}public void setPwd(String pwd) {    this.pwd = pwd;}public int getAge() {    return age;}public void setAge(int age) {    this.age = age;} }

2. Compile the factory class for database connection:
package cn.netjava.factory; import java.sql.Connection;import java.sql.DriverManager; public class Connect2DBFactory {    public static Connection getDBConnection() {        Connection conn = null;        try {            Class.forName(com.mysql.jdbc.Driver);            String url = jdbc:mysql://localhost:3306/blogsystem;            String user = root;            String password = netjava;            conn = DriverManager.getConnection(url, user, password);        } catch (Exception e) {            e.printStackTrace();        }         return conn;    }}

 

3. Let's get started. Write the dao class for database operations.

Package cn. netjava. session; import java. lang. reflect. field; import java. lang. reflect. method; import java. SQL. connection; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement; import java. util. arrayList; import java. util. list; import cn. netjava. factory. connect2DBFactory; import cn. netjava. pojo. userInfo; public class NetJavaSession {/*** parses the SQL statement ** @ param object *: object to be saved * @ return: save the Object's SQL statement */public static String getSaveObjectSql (object) {// define an SQL String SQL = insert into; // obtain the Object Class c = object. getClass (); // obtain all methods of the object. Method [] methods = c. getMethods (); // obtain all attributes of the Field [] fields = c. getFields (); // obtain the object class name String cName = c. getName (); // parse the table name String tableName = cName from the class name. substring (cName. lastIndexOf (.) + 1, cName. length (); SQL + = tableName + (; List
 
  
MList = new ArrayList
  
   
(); List vList = new ArrayList (); for (Method method: methods) {String mName = method. getName (); if (mName. startsWith (get )&&! MName. startsWith (getClass) {String fieldName = mName. substring (3, mName. length (); mList. add (fieldName); System. out. println (field name -----> + fieldName); try {Object value = method. invoke (object, null); System. out. println (value returned by the execution method: + value); if (value instanceof String) {vList. add (+ value +); System. out. println (field value ------> + value);} else {vList. add (value) ;}} catch (Exception e) {e. printStackTrace () ;}}for (int I = 0; I <mList. size (); I ++) {if (I <mList. size ()-1) {SQL + = mList. get (I) +,;} else {SQL + = mList. get (I) +) values (;}}for (int I = 0; I <vList. size (); I ++) {if (I <vList. size ()-1) {SQL + = vList. get (I) +,;} else {SQL + = vList. get (I) +) ;}} return SQL;} public static List getDatasFromDB (String tableName, int Id) {return null ;} /*** Save the object to the database ** @ param object *: the object to be saved * @ return: Result of method execution; 1: indicates success, 0: */public int saveObject (Object object) {Connection con = Connect2DBFactory. getDBConnection (); String SQL = getSaveObjectSql (object); try {// Statement statement = (Statement) con. createStatement (); PreparedStatement psmt = con. prepareStatement (SQL); psmt.exe cuteUpdate (); return 1;} catch (SQLException e) {e. printStackTrace (); return 0 ;}/ *** obtain the object from the database ** @ param arg0 *: class of the object * @ param id *: object id * @ return: the Object to be searched */public Object getObject (String className, int Id) {// obtain the table name String tableName = className. substring (className. lastIndexOf (.) + 1, className. length (); // create the Class Object Class c = null based on the Class name; try {c = Class. forName (className);} catch (ClassNotFoundException e1) {e1.printStackTrace ();} // patchwork query SQL statement String SQL = select * from + tableName + where Id = + Id; System. out. println (query SQL statement: + SQL); // obtain the database Connection con = Connect2DBFactory. getDBConnection (); // create an instance of the Class Object obj = null; try {Statement stm = con. createStatement (); // obtain the result set ResultSet set = cmd.exe cuteQuery (SQL) returned by the query statement. // obtain the Method array of the object. Method [] methods = c. getMethods (); // traverses the result set while (set. next () {obj = c. newInstance (); // Method for Traversing objects for (method: methods) {String methodName = Method. getName (); // if the object's method starts with set if (methodName. startsWith (set) {// obtain the field name String columnName = methodName in the data table based on the method name. substring (3, methodName. length (); // obtain the parameter type of the method. Class [] parmts = method. getParameterTypes (); if (parmts [0] = String. class) {// If the parameter is of the String type, the corresponding value is obtained from the result set according to the column name, And the set method is modified. invoke (obj, set. getString (columnName);} if (parmts [0] = int. class) {method. invoke (obj, set. getInt (columnName) ;}}}} catch (Exception e) {e. printStackTrace ();} return obj ;}}
  
 

 

4. How is the test result:

Package cn. netjava. tester; import cn. netjava. pojo. userInfo; import cn. netjava. session. netJavaSession; public class Tester {public static void main (String args []) {// obtain the NetJavaSession object NetJavaSession session = new NetJavaSession (); // create a UserInfo object UserInfo user = new UserInfo (); // set the property user of the object. setId (6988); user. setAge (44); user. setPwd (pwd); user. setName (champion); // Save the object to the database. String SQL = session. getSaveObjectSql (user); System. out. println (SQL statement for saving the object: + SQL); // query the UserInfo userInfo = (UserInfo) session of the object. getObject (cn. netjava. pojo. userInfo, 6988); System. out. println (obtained information: + userInfo );}}

 

5. Printed results:

 

The following is a good example:

 

Steps for compiling a Java reflection program:
1) You must first obtain the Class object of a Class.
For example:
Class c1 = Test. class;
Class c2 = Class. forName ("com. reflection. Test ");
Class c3 = new Test (). getClass ();
2) Call the methods in the Class object to obtain the attributes/methods/constructor structure of a Class.
Note: If you want to obtain methods, properties, and constructor in the class, you should focus on the following reflection classes.
Field
Constructor
Method
Example: The program example shows you how to operate classes related to Java reflection, such as Class/Field/Constructor/Method.
  

Package com. reflection; import java. lang. reflect. constructor; import java. lang. reflect. field; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method; import java. lang. reflect. modifier; public class TestReflection {private String username; private String password; private int [] age; public void setUserName (String username) {this. username = username;} private void setPassWord (String password) {this. password = password;} public static void test01 () throws ClassNotFoundException {Class c1 = TestReflection. class; Class c2 = Class. forName (com. reflection. testReflection); // obtain the specified package name String package01 = c1.getPackage (). getName (); String package02 = c2.getPackage (). getName (); System. out. println (package01 = + package01); System. out. println (package02 = + package02); // get the class modifier int mod = c1.getModifiers (); String Modifier = modifier. toString (mod); System. out. println (modifier = + modifier); // obtain the fully qualified name of the specified class String className = c1.getName (); System. out. println (className = + className); // obtain the parent Class superClazz = c1.getSuperclass () of the specified Class; String superClazzName = superClazz. getName (); System. out. println (superClazzName = + superClazzName); // obtain the implemented interface Class [] interfaces = c1.getInterfaces (); for (Class t: interfaces) {System. out. println (interfacesName = + t. getName ();} // obtain the Field [] fields = c1.getDeclaredFields (); for (Field field Field: fields) {modifier = Modifier. toString (field. getModifiers (); // obtains the access modifier Class type = field for each field. getType (); // Class object corresponding to the Data Type of the obtained field String name = field. getName (); // obtain the field name if (type. isArray () {// if it is an array type, special processing is required for String arrType = type. getComponentType (). getName () + []; System. out. println (+ modifier ++ arrType ++ name ++;);} else {System. out. println (+ modifier ++ type ++ name ++;) ;}// obtain the Constructor [] constructors = c1.getDeclaredConstructors (); for (constructor Constructor: constructors) {String name = constructor. getName (); // constructor name modifier = Modifier. toString (constructor. getModifiers (); // get the access modifier System. out. println (+ modifier ++ name + (); Class [] paramTypes = constructor. getParameterTypes (); // obtain the for (int I = 0; I <paramTypes. length; I ++) {if (I> 0) {System. out. print (,);} if (paramTypes [I]. isArray () {System. out. println (paramTypes [I]. getComponentType (). getName () + []);} else {System. out. print (paramTypes [I]. getName () ;}} System. out. println ();} // obtain the member Method [] methods = c1.getDeclaredMethods (); for (Method method: methods) {modifier = Modifier. toString (method. getModifiers (); Class returnType = method. getReturnType (); // returns the type of the method if (returnType. isArray () {String arrType = returnType. getComponentType (). getName () + []; System. out. print (+ modifier ++ arrType ++ method. getName () + ();} else {System. out. print (+ modifier ++ returnType. getName () ++ method. getName () + ();} Class [] paramTypes = method. getParameterTypes (); for (int I = 0; I <paramTypes. length; I ++) {if (I> 0) {System. out. print (,);} if (paramTypes [I]. isArray () {System. out. println (paramTypes [I]. getComponentType (). getName () + []);} else {System. out. print (paramTypes [I]. getName () ;}} System. out. println ();) ;}} public static void test02 () throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {// reflection call method, you can call a dynamic Method using the invoke Method of the Method class // public Object invoke (Object obj, Object... args) // The first parameter represents the object // The second parameter represents the parameter on the execution method // If reflection is required to call a private method of the class, you can call setAccessible (true) Class c1 = TestReflection on the mehtop object corresponding to this private method. class; TestReflection t1 = (TestReflection) c1.newInstance (); // use reflection to create the class Object System. out. println (username = + t1.username); System. out. println (password = + t1.password); Method method = c1.getDeclaredMethod (setUserName, String. class); method. invoke (t1, Java reflection learning); System. out. println (username = + t1.username); method = c1.getDeclaredMethod (setPassWord, String. class); method. setAccessible (true); method. invoke (t1, reflection executes a Private modifier); System. out. println (password = + t1.password);} public static void main (String [] args) throws ClassNotFoundException, SecurityException, exceptions, InstantiationException, IllegalAccessException, NoSuchMethodException, invocationTargetException {// test01 (); test02 ();}}

 

VII. Summary

In general, the java reflection mechanism is a very useful thing. It can solve a lot of dead things, because the reflection mechanism is flexible and flexible, we should not spend too much time writing code for database operations, but spend more time on the project's logical functions, which can greatly reduce the development time, the Code is also readable. Many open-source frameworks use the reflection mechanism only. It only needs to configure the file and then call its method according to the rules.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.