Use reflection to assign values to the corresponding entity class's properties after reading from the database

Source: Internet
Author: User
Tags class definition modifier

1. Connect the database and close the connection (Jdbctools.java)
Package Com.xiaojie.dao;import Java.io.ioexception;import Java.sql.connection;import java.sql.PreparedStatement; Import Java.sql.resultset;import Java.sql.sqlexception;import Javax.sql.datasource;import      Com.mchange.v2.c3p0.combopooleddatasource;public class Jdbctools {private static DataSource ds=null;      The database connection pool should be initialized only once static{ds=new Combopooleddatasource ("helloc3p0");          }//Get database connection public static Connection getconnection () throws ClassNotFoundException, SQLException, ioexception{          return Ds.getconnection (); } public static void Shifanglianjie (Connection ct, preparedstatement ps,resultset rs) {if (rs!=null) {try {RS.C Lose ();}    catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}    } if (Ps!=null) {try {ps.close ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} } if (Ct!=null) {try {ct.close ()} catch (SQLException e) {//TODO auto-generated catch BLOCKE.PRintstacktrace ();} }    }}
2. DAO Module
Package Com.xiaojie.dao;import Java.io.ioexception;import Java.sql.connection;import java.sql.PreparedStatement; Import Java.sql.resultset;import java.sql.resultsetmetadata;import java.sql.statement;import java.util.ArrayList; Import Java.util.date;import java.util.hashmap;import Java.util.list;import Java.util.map;import Com.xiaojie.beans.trade;import Java.sql.sqlexception;public class Dao<t> {//query a record, return the corresponding object public <T> T Query (class<t> clazz,string sql,object...args) {T example=null; Connection Ct=null; PreparedStatement Ps=null; ResultSet Rs=null;try {//1, get connectionct=jdbctools.getconnection (); SYSTEM.OUT.PRINTLN ("Query gets connected to the database");//2, get Preparedstatementps=ct.preparestatement (SQL);//3, fill placeholder for (int i=0;i <args.length;i++) {ps.setobject (i+1, args[i]);} 4, make inquiries, get Resultsetrs=ps.executequery ();//5, prepare a map<string,object>:(if the result set should be recorded) if (Rs.next ()) {map< String,object> values=new hashmap<string,object> ();//6, ResultSetMetaData object ResultSetMetaData rsd= Rs.getmEtadata ();//7, handles resultset, moves the pointer down one unit//8, the ResultSetMetaData object gets the number of columns in the result set, int lieshu=rsd.getcolumncount ();//9, The alias of each column is obtained by the ResultSetMetaData object, and the value for each column is given by resultset for (int i=0;i<lieshu;i++) {String Lieming=rsd.getcolumnlabel (i +1); object Liezhi=rs.getobject (i+1);//10, fill Map Object Values.put (Lieming,liezhi);} 11. Create a class corresponding Object Example=clazz.newinstance () with reflection,//12, traverse the Map object, fill the object's attribute value with reflection, for (map.entry<string, object> ent : Values.entryset ()) {String name=ent.getkey (); Object value=ent.getvalue ();//With Reflection assignment Reflectionutils.setfieldvalue ( example, name, value);}}} catch (Exception e) {e.printstacktrace ();} Finally{jdbctools.shifanglianjie (CT, PS, RS);} return example;} Querying multiple records, returning multiple corresponding objects public list<t> querylist (class<t> clazz,string sql,object...args) {T example=null; Connection Ct=null; PreparedStatement Ps=null; ResultSet Rs=null; List li=new ArrayList (); try {//1, get connectionct=jdbctools.getconnection (); System.out.println ("Querylist gets a connection to the database");//2, get Preparedstatementps=ct.preparestatement (SQL);//3, fill placeholder For (int i=0;i<args.length;i++) {ps.setobject (i+1, args[i]);} 4, make inquiries, get Resultsetrs=ps.executequery ();//5, prepare a map<string,object>:(if the result set is recorded) while (Rs.next ()) {Map <String,Object> values=new hashmap<string,object> ();//6, get ResultSetMetaData object ResultSetMetaData rsd= Rs.getmetadata ();//7, handles resultset, moves the pointer down one unit//8, the ResultSetMetaData object gets the number of columns in the result set, int lieshu=rsd.getcolumncount (); /9, the alias of each column is obtained by the ResultSetMetaData object, and the value of each column is given by resultset for (int i=0;i<lieshu;i++) {String lieming= Rsd.getcolumnlabel (i+1); object Liezhi=rs.getobject (i+1);//10, fill Map Object Values.put (Lieming,liezhi);} 11. Create a class corresponding Object Example=clazz.newinstance () with reflection,//12, traverse the Map object, fill the object's attribute value with reflection, for (map.entry<string, object> ent : Values.entryset ()) {String name=ent.getkey (); Object value=ent.getvalue ();//With Reflection assignment Reflectionutils.setfieldvalue ( example, name, value);} Li.add (example);}} catch (Exception e) {e.printstacktrace ();} Finally{jdbctools.shifanglianjie (CT, PS, RS);} return li;}}


3. Reflective Tool Class
Package Com.xiaojie.dao;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.lang.reflect.modifier;import Java.lang.reflect.parameterizedtype;import java.lang.reflect.type;/** * reflected Utils function set * Provides access to private variables, gets generic type class, extracts Utils functions such as element properties in the collection * @author Administrator * */PUBL IC class Reflectionutils {/** * through reflection, gets the type of the generic parameter of the parent class declared when the class is defined * such as: public EmployeeDAO extends Basedao<employee, Strin g> * @param clazz * @param index * @return */@SuppressWarnings ("unchecked") public static Class Getsuperclassgenrictype ( Class clazz, int index) {Type gentype = Clazz.getgenericsuperclass (); Gentype instanceof Parameterizedtype) {return object.class;} Type [] params = ((Parameterizedtype) gentype). Getactualtypearguments (); if (index >= params.length | | Index < 0) { return object.class;} if (! ( Params[index] instanceof Class) {return object.class;} Return (Class) Params[index];} /** * Through reflection, get the generic parameter type of the parent class declared in the class definition * such as: public EMPLoyeedao extends Basedao<employee, string> * @param <T> * @param clazz * @return */@SuppressWarnings ("Unchecke D ") Public static<t> class<t> Getsupergenerictype (Class clazz) {return Getsuperclassgenrictype (clazz, 0);} /** * cycle up, get Declaredmethod * @param object * @param methodName * @param parametertypes * @return */public static M Ethod Getdeclaredmethod (Object object, String methodName, class<?>[] parametertypes) {for (class<?> Superclass = Object.getclass (); Superclass! = Object.class; Superclass = Superclass.getsuperclass ()) {try {//superclass.getmethod (methodName, parametertypes); return Superclass.getdeclaredmethod (MethodName, parametertypes);} catch (Nosuchmethodexception e) {//method is not in the current class definition, continue to transition upward}//...} return null;} /** * makes filed accessible * @param field */public static void makeaccessible (Field field) {if (! Modifier.ispublic (Field.getmodifiers ())) {field.setaccessible (true);}} /** * cycle up, get Declaredfield * @param object * @param filedname * @reTurn */public static Field Getdeclaredfield (Object object, String filedname) {for (class<?> superclass = Object.getclass (); Superclass! = Object.class; Superclass = Superclass.getsuperclass ()) {try {return Superclass.getdeclaredfield (filedname);} catch ( Nosuchfieldexception e) {//field is not in the current class definition, continue to transition upward}}return null;}  /** * Call object method directly, ignoring modifier (private, Protected) * @param object * @param methodName * @param parametertypes * @param parameters * @return * @throws invocationtargetexception * @throws illegalargumentexception */public static Object InvokeMethod (Ob Ject object, String methodName, class<?> [] parametertypes,object [] parameters) throws invocationtargetexception{ METHOD = Getdeclaredmethod (object, MethodName, parametertypes); if (method = = null) {throw new IllegalArgumentException ("Could not Find method [" + MethodName + "] on target [" + Object + "]");} Method.setaccessible (true); try {return Method.invoke (object, parameters);} catch (Illegalaccessexception e) { System.out. println ("an exception that cannot be thrown");} return null;} /** * Directly Sets object property values, ignores private/protected modifiers, and does not pass Setter * @param object * @param fieldName * @param value */public static V OID SetFieldValue (Object object, String fieldName, Object value) {Field field = Getdeclaredfield (object, FieldName), if (fi Eld = = null) throw new IllegalArgumentException ("Could not the Find field [" + FieldName + "] on target [" + Object + "]"); Accessible (field); try {Field.set (object, value);} catch (Illegalaccessexception e) {System.out.println ("exception not possible to throw");}} /** * Directly reads the object's property values, ignores the private/protected modifier, and does not go through getter * @param object * @param fieldName * @return */public static objec T GetFieldValue (Object object, String fieldName) {Field field = Getdeclaredfield (object, FieldName); if (Field = = null) thro W New IllegalArgumentException ("Could not find field [" + FieldName + "] on target [" + Object + "]"); Makeaccessible (field Object result = Null;try {result = Field.get (Object),} catch (Illegalaccessexception e) {System.out.println ("cannot throwException ");} return result;}}
4, the database corresponding to the JavaBeans entity class
Package Com.xiaojie.beans;import Java.util.date;public class Trade {private int tradeid;private int userid;private Date t radetime;public int Gettradeid () {return tradeid;} public void Settradeid (int tradeid) {This.tradeid = TradeID;} public int GetUserid () {return userid;} public void Setuserid (int userid) {this.userid = userid;} Public Date Gettradetime () {return tradetime;} public void Settradetime (Date tradetime) {this.tradetime = Tradetime;}  Public trade (int tradeid, int userid, Date tradetime) {super (); This.tradeid = Tradeid;this.userid = Userid;this.tradetime = Tradetime;} Public trade () {super ();}}
5, write a test class to try the effect (if the imported jar package is imported, and the database has a corresponding JavaBeans table, c3p0 configuration files, etc. are all set up)
Package Com.xiaojie.test;import Java.io.ioexception;import Java.sql.date;import java.sql.sqlexception;import Java.util.arraylist;import Java.util.list;import Org.junit.test;import Com.xiaojie.beans.trade;import Com.xiaojie.dao.dao;public class Daotest {private DAO dao=new dao (); <span style= "White-space:pre" ></span> The following test method is to test an attribute assignment that queries a record from the database to the corresponding JavaBean, and displays a print result @testpublic void Testquery () throws classnotfoundexception in the console, SQLException, ioexception{string sql= "SELECT * from trade where tradeid=?"; Trade trade=new Trade (), trade= (trade) dao.query (trade.class,sql,1); System.out.println ("TradeID:" +trade.gettradeid () + "\nuserid:" +trade.getuserid () + "\ntradetiem:" + Trade.gettradetime ());} The following test method is to assign a value to the corresponding JavaBean property from the results of a database query (more than one record) and display multiple print results @testpublic void testquerylist () {String sql= "select *) in the console from trade "; Trade trade=new Trade (); List<trade>trades=new arraylist<trade> (); trades= (list<trade>) dao.querylist (Trade.class,sql); for (trade trade1:trades) {SYSTEM.OUT.PRINtln ("TradeID:" +trade1.gettradeid () + "\nuserid:" +trade1.getuserid () + "\ntradetiem:" +trade1.gettradetime ());}} 


Use reflection to assign values to the corresponding entity class's properties after reading from the database

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.