Learning Summary of Java reflection mechanism _java

Source: Internet
Author: User
Tags object object reflection

One, 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, given the name of a class, all the information about the class can be obtained through the reflection mechanism.

Second, where to use the reflection mechanism
Sometimes we use some knowledge, but we don't know what the terminology is, we used a line of code when we just learned JDBC, class.forname ("Com.mysql.jdbc.Driver.class"). newinstance (); But at that time only knew that line of code is the build Drive object instance, does not know its concrete meaning. After listening to the reflection mechanism this lesson, just know, originally this is the reflection, now many open the frame all uses the reflection mechanism, hibernate, struts all is realizes with the reflection mechanism.

Iii. advantages and disadvantages of reflection mechanism
Why should we use reflex mechanism? Creating objects directly is not OK, this involves the concept of dynamic and static,
static compilation: determines the type at compile time, binds the object, that is, through.

Dynamic Compilation: The runtime determines the type and binds the object. Dynamic compilation maximizes the flexibility of Java, embodies the application of polymorphism, and reduces the coupling between classes.

In a word, the advantage of reflection mechanism is that it can achieve dynamic creation of objects and compile, which embodies great flexibility, especially in the development of Java EE, its flexibility is very obvious. For example, a large software, it is not possible to put it in a perfect design, when the program compiled, released, when the discovery needs to update some features, we can not have the user to the previous uninstall, and then reinstall the new version, if so, this software is certainly not how many people use. Static, you need to recompile the entire program to achieve the function of the update, and the use of reflection mechanism, it can not uninstall, only to be dynamic in the runtime to create and compile, you can achieve this function.

Its disadvantage is that it has an impact on performance. Using reflection is basically an interpretation operation, we can tell the JVM what we want to do and it meets our requirements. Such operations are always slower than performing the same operations directly.

Iv. what information can be obtained using the reflection mechanism
In a word, the class has any information, it can get what information, but the premise is to know the name of the class, or there is no later text first, based on the full name of the incoming class to create a class object.

Class c=class.forname ("ClassName"), Annotated: ClassName must be full name, that is to include the package name, for example, Cn.netjava.pojo.UserInfo;
Object Obj=c.newinstance ();//Create an instance of a
OK, with the object will be good to do anything, want what information have what information.
Methods to get constructors
Constructor GetConstructor (class[] params)//Get public constructor based on specified parameters

Constructor[] GetConstructors ()//Get all constructors for public

Constructor Getdeclaredconstructor (class[] params)/To obtain public and non-public constructors based on the specified parameters

Constructor[] Getdeclaredconstructors ()//Get all constructors for public

Methods for obtaining a class method
Method GetMethod (String name, class[] params), according to the method name, the parameter type to obtain methods

Method[] GetMethods ()//Get all public methods

Method Getdeclaredmethod (String name, class[] params)//To obtain public and Non-public methods based on method name and parameter type

Method[] Getdeclaredmethods ()//Get the public and Non-public methods

Methods for obtaining attributes in a class
Field GetField (String name)//the corresponding public variable based on the variable name

Field[] GetFields ()//Get the method for public in the class

Field Getdeclaredfield (String name)//To obtain public and Non-public variables based on method name

Field[]//Get all public and Non-public methods in the class, Getdeclaredfields ()
Commonly used in this, know these, others are good to do ...

V. What can be done with the reflection mechanism
When you first started using JDBC, when writing to the database to write to vomit, there are eight tables, each table has an increase in the operation of the check, and then did not know the concept of reflection mechanism, so the different tables to create a different DAO class, so not only the development rate, and the code redundancy is bad, The most deadly is to look at the same, and then directly copy the changes, due to easy to make a variety of low-level errors (ah, one or less letter ah ... , a mistake will allow you to find half a day.

With the Java reflection mechanism, what is good to do, just write a DAO class, four methods, additions and deletions, incoming different objects, OK, no need for each table to create DAO class, reflection mechanism will automatically help us complete the rest of the things, this is its benefits. Plainly, the reflection mechanism is specifically to help us do those repetitive rules of things, so now a lot of automatic generation of code software is to use the reflection mechanism to complete, as long as you enter the relevant parameters according to the rules, so low-level programmers are slowly erased, why? Because the code does not need to write, any person will develop, but also programmers do ah? So we only have one way out, that is to work hard again, become senior programmers, specialized development fool software, let other programmers to the side cool go, hehe ~

Using reflection mechanism to achieve the increase of database data, search examples
Basic principles; When you save the data, all the property values of the objects you need to save are taken out and then the query to the SQL query is packaged into a Java object.

Rules of the game: as the saying goes, no rules radius, especially the program, it can only do things with rules, there is no rule of it can not do, well, then first set the rules
1 Each Table object in the database is a Pojo class, and each field in the table corresponds to a property in the Pojo class. and the name of the Pojo class is the same as the name of the table, the property name and the field name are the same, the case is not related because the database is generally case-insensitive

2 Add the standard set and get methods for each property in the Pojo class.
With the rules of the game, let's start the game.

1, the first database has a table, assuming the database name is: Blogsystem, the inside of a table name UserInfo. As shown in figure:


2, create the corresponding Pojo class:

Copy Code code as follows:



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 age) {


This.age = age;


}





}





2, write to obtain the database connection factory class:


Copy Code code as follows:



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, the fun begins, write the DAO class that manipulate the database


Copy Code code as follows:



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 out the SQL statement to save the object


*


* @param Object


*: Objects that need to be saved


* @return: Save an object's SQL statement


*/


public static String Getsaveobjectsql (Object object) {


Define an SQL string


String sql = "INSERT INTO";


The class that gets the object


Class C = Object.getclass ();


Get all the methods in the object


Method[] methods = C.getmethods ();


Get all the attributes in the object


field[] fields = C.getfields ();


Get the name of the object class


String cName = C.getname ();


To parse a table name from the name of a 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: Results of method execution; 1: Success, 0: Indicates failure


*/


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


*: The 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 name of the table


String tablename = classname.substring (Classname.lastindexof (".") + 1,


Classname.length ());


To create a class object based on the class name


Class c = null;


try {


c = Class.forName (ClassName);





catch (ClassNotFoundException E1) {





E1.printstacktrace ();


}


Piecing together 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 execution lookup statement


ResultSet set = Stm.executequery (SQL);


Gets an array of methods for the object


Method[] methods = C.getmethods ();


Traverse result set


while (Set.next ()) {


obj = C.newinstance ();


Ways to traverse objects


For (method Method:methods) {


String methodname = Method.getname ();


If the object's method starts with set


if (Methodname.startswith ("set")) {


The name of the field in the data table according to 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 parameter is of type string, the corresponding value is obtained from the result set by the column name, and the Modify 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 test results:


Copy Code code as follows:



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 in a database


String sql = session.getsaveobjectsql (user);


System.out.println ("Save the object's SQL statement:" + SQL);


Finding objects


UserInfo UserInfo = (UserInfo) session.getobject (


"Cn.netjava.pojo.UserInfo", 6988);


SYSTEM.OUT.PRINTLN ("Obtained information:" + userInfo);





}


}





5, print out the results:





Seven, the general section
In general, the Java reflection mechanism is a very useful thing to use it to solve a lot of dead things, because the reflective mechanism of the flexible line is very large, with him, we do not spend too much time to write the code to do the database, but the method more time in the project's logical function, this can greatly reduce the development time, And the code is very readable. Many of the open source frameworks are used only for the reflection mechanism, as long as the configuration file, and then follow the rules to call his method.

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.