Original address: http://www.cnblogs.com/jqyp/archive/2012/03/29/2423112.html#undefined
First, what is the reflection mechanism
In simple terms, the reflection mechanism refers to the ability of a program to obtain its own information at run time. In Java, as long as the name of the given class,
You can then use the reflection mechanism to get all the information about the class.
Second, where to use the reflection mechanism
Sometimes we use some knowledge, but we don't know what the terminology is, and when we just learned JDBC we used a line of code,
Class.forName ("Com.mysql.jdbc.Driver.class"). newinstance (); But then only knew that line of code was generated
Drive an object instance without knowing its specific meaning. After listening to the reflection mechanism this lesson, only then knew, originally this is the reflection, now many open
The framework uses a reflection mechanism, and hibernate and struts are implemented using the reflection mechanism.
The advantages and disadvantages of the reflection mechanism
Why use a reflection mechanism? Creating objects directly doesn't make sense, it involves the concept of dynamic and static,
Static compilation: Determines the type at compile time, binds the object, which is passed.
Dynamic compilation: The runtime determines the type, binding object. Dynamic compilation maximizes the flexibility of Java and embodies many
To reduce the coupling of the classes.
In a word, the advantage of the reflection mechanism is that it can achieve dynamic creation of objects and compile, showing great flexibility, especially in the development of the Java EE
Its flexibility is very obvious. For example, a large software, it is impossible to put it in a perfect design, when the program is compiled
After the release, when the discovery needs to update some features, we can not want users to put the previous uninstall, and then reinstall the new version, if
In this case, this software is certainly not many people use. With static words, the entire program needs to be recompiled once to achieve the function
, and with the reflection mechanism, it can be created and compiled dynamically without the need to unload, and the work can be implemented
Yes.
Its disadvantage is that it has an impact on performance. Using reflection is basically an interpretation operation, and we can tell the JVM what we want to do and it
To meet our requirements. This type of operation is always slower than just performing the same operation directly.
Iv. what information can be obtained by using the reflection mechanism
In a word, the class has what information, it can get what information, but the premise is to know the name of the class, or there is no post-text
You first have to create a class object based on the full name of the class passed in.
Class c=class.forname ("ClassName"); Note: ClassName must be the full name, that is, include the package name, for example, Cn.netjava.pojo.UserInfo;
Object Obj=c.newinstance ();//Create an instance of an object
OK, with the object is all right, what information you want to have what information.
How to get a constructor function
Constructor GetConstructor (class[] params)//Get public constructor based on specified parameters
Constructor[] GetConstructors ()//all constructors for public
Constructor getdeclaredconstructor (class[] params)//Get public and non-public constructors based on specified parameters
Constructor[] Getdeclaredconstructors ()//all constructors for public
Methods of obtaining class methods
Method GetMethod (String name, class[] params), obtained by method name, parameter type
Method[] GetMethods ()//Get all the public methods
Method Getdeclaredmethod (String name, class[] params)//Get public and non-public methods based on method name and parameter type
Method[] Getdeclaredmethods ()//get so public and non-public methods
Methods for obtaining properties in a class
Field GetField (String name)//Get the appropriate public variable based on the variable name
Field[] GetFields ()//Get the method of public in class
Field Getdeclaredfield (String name)//Get public and non-public variables by method name
Field[] Getdeclaredfields ()//Get all public and non-public methods in the class
This is the usual, knowing this, the rest is good.
V. What can be done with reflection mechanism
At first, when using JDBC, when writing access to the database to write to want to vomit, there are eight tables, each table has an add-and-remove operation
It was not known at the time that there was a concept of reflection mechanism, so we created different DAO classes for different tables, so that not only the rate of development, but also the code
Redundant, the most deadly is to look at the same, and then directly copy the changes, because it is easy to make a variety of low-level errors (case, more than one
One or a few letters ... ), an error can make you look for half a day.
With the Java reflection mechanism, what is good to do, just want to write a DAO class, four methods, additions and deletions to check, incoming different objects, OK,
Instead of creating a DAO class for each table, the reflection mechanism automatically helps us do the rest, which is the benefit. Frankly, the reflection mechanism is specifically
Help us do those repetitive and regular things, so now a lot of automatic code generation software is to use the reflection mechanism to do, as long as you follow the rules
Input related parameters, so the low-level programmer slowly is erased, why? Because the code does not have to write, any person will develop, but also the process
What do the sequencer do? So we have only one way out, that is, efforts to work hard again, become a senior programmer, specializing in the development of fool software, so that other programmers to cool off, hehe ~
Vi. using reflection mechanism to realize the example of database data increasing and checking
The basic principle; When you save the data, take all the property values of the objects you want to save and then piece together the SQL statements
When you query, all the data that you query is wrapped into a Java object.
Game rules: As the saying goes, no rules inadequate surrounding area, especially the program, it can only do the rules of things, no rules it can not do, good, then
Set rules first
1) Each Table object in the database is a Pojo class, and each field in the table corresponds to an attribute in the Pojo class.
and the name of the Pojo class is the same as the name of the table, the property name is the same as the field name, and the capitalization is not related, because the database is generally case insensitive
2) Add standard set and get methods for each attribute in the Pojo class.
With the rules of the game, start the game.
1, the first database has a table, assuming that the database name is: Blogsystem, inside a table name 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;
@Override
Public 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.) {
This.age = age;
}
}
2. Write the factory class that gets the 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. Start the game, write the DAO class that operates the database
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 {
/**
* Parse the SQL statement that saved the object
*
* @param Object
*: Objects that need to be saved
* @return: Save an object's SQL statement
*/
public static String Getsaveobjectsql (Object object) {
Define a SQL string
String sql = "INSERT INTO";
Gets the class of the object
Class C = Object.getclass ();
Get all the methods in the object
Method[] methods = C.getmethods ();
Get all the properties in the object
field[] fields = C.getfields ();
Get the name of the object class
String cName = C.getname ();
Parse the table name from the name of the class
String tableName = cname.substring (Cname.lastindexof (".") + 1,
Cname.length ());
SQL + = TableName + "(";
list<string> mlist = new arraylist<string> ();
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 ("The 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
*: Objects that need to be saved
* @return: Result of method execution; 1: Success, 0: Failed
*/
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.executeupdate ();
return 1;
} catch (SQLException e) {
E.printstacktrace ();
return 0;
}
}
/**
* Get objects from the database
*
* @param arg0
*: Class to which the object belongs
* @param ID
*: ID of Object
* @return: Objects to look for
*/
Public Object GetObject (String className, int Id) {
Get the table name
String tableName = classname.substring (Classname.lastindexof (".") + 1,
Classname.length ());
To create a class object based on its name
Class c = null;
try {
c = Class.forName (ClassName);
} catch (ClassNotFoundException E1) {
E1.printstacktrace ();
}
Patchwork Query SQL statements
String sql = "SELECT * from" + TableName + "where id=" + Id;
SYSTEM.OUT.PRINTLN ("Find SQL statement:" + SQL);
Get Database Links
Connection con = connect2dbfactory.getdbconnection ();
To create an instance of a class
Object obj = null;
try {
Statement stm = Con.createstatement ();
Gets the result set returned by the Execute lookup statement
ResultSet set = Stm.executequery (SQL);
Get an array of methods for an object
Method[] methods = C.getmethods ();
Traversing result Sets
while (Set.next ()) {
obj = C.newinstance ();
Methods for traversing objects
for (Method method:methods) {
String methodName = Method.getname ();
If the object's method starts with a set
if (Methodname.startswith ("set")) {
Get the name of the field in the data table based on the method name
String columnName = methodname.substring (3,
Methodname.length ());
Get the parameter type of the method
class[] Parmts = Method.getparametertypes ();
if (parmts[0] = = String.class) {
If the argument is of type string, the corresponding value is obtained from the result set according to the column name, and the change set method is executed
Method.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 to start the test effect:
Package cn.netjava.tester;
Import Cn.netjava.pojo.UserInfo;
Import cn.netjava.session.NetJavaSession;
public class Tester {
public static void Main (String args[]) {
Get Netjavasession Object
Netjavasession session = new Netjavasession ();
Create a UserInfo object
UserInfo user = new UserInfo ();
Set the properties of an object
User.setid (6988);
User.setage (44);
User.setpwd ("pwd");
User.setname ("Champion");
To save an object to the database
String sql = session.getsaveobjectsql (user);
System.out.println ("Save the object's SQL statement:" + SQL);
Find objects
UserInfo UserInfo = (UserInfo) session.getobject (
"Cn.netjava.pojo.UserInfo", 6988);
SYSTEM.OUT.PRINTLN ("Information obtained:" + userInfo);
}
}
5, print out the result:
Vii. General Section
In general, the Java reflection mechanism is a very useful thing, with it can solve a lot of dead things, because of the flexibility of the reflection mechanism is very large, with him, we do not spend too much time to write the code of the database, but the method more time in the logical function of the project, this can greatly reduce development time, And the code is very readable. Many of the first open source frameworks are just the reflection mechanism, which is just a configuration file and then the rules to invoke his method.
Note: This blog post is for individual study notes only
Java reflection of the understanding and application (a great God blog to see the blog, write really good, decisive reprint as a note)