JAKARTA-Common-BeanUtils Study (2)

xiaoxiao2021-03-06  70

Author: Sonymusic 2003.05.13 6, CONSTRUCTORUTILS Recreation Objects There is also a method: InvokeExactConstructor, this method is more stringent to parameters, and the parameters passing must strictly meet the parameter list of constructors. For example: Object [] args = {new integer (1), "jan"}; class [] argstype = {int.class, string.class}; object obj; // This call will not succeed because args [0] The type is Integer instead of int // Obj = constructorutils.invokeexactConstructor (Month.class, args); // This sentence can be, because ArgStype specifies the type. obj = ConstructorUtils.invokeExactConstructor (Month.class, args, argsType); Month month = (Month) obj; System.out.println (BeanUtils.getProperty (month, "value")); seven, MethodUtils and ConstructorUtils similar, but calls When you need to specify a parameter of a Method Name again. Eight, Dynaclass / Dynabean seems to be one of the most interesting parts in Beanutils. It is very simple. Simple to light. The method in these two interfaces does not understand why it is designed to design these two interfaces. However, after seeing ResultSetDynaclass, I understand. Here is the code in Java DOC: ResultSet RS = ...; ResultSetDynaclass RSDC = New ResultSetDynaclass (RS); item Rows = RSDC.ITerator (); while (rows.hasnext ()) {Dynabean Row = (Dynabean) Rows. Next (); ... process this rot ...} rs.close (); It turns out that this is a RESULTSET wrapper, resultSetdyNaclass implements Dynaclass, and its Iterator method returns a ResultSetiterator, which is the Dynabean interface.

After getting a Dynabean, we can use Dynabean Row = (Dynabean) rows.next (); system.out.println (Row.Get ("Field1")); // Field1 is the name of one of the fields to see another a class RowSetDynaClass usage, the code is as follows: String driver = "com.mysql.jdbc.Driver"; String url = "jdbc: mysql: // localhost / 2hu useUnicode = true & characterEncoding = GBK?"; String username = "root"; String password = ""; java.sql.Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try {Class.forName (driver) .newInstance (); con = DriverManager.getConnection (url); ps = con .preparestatement ("Select * from forumlist"); RS = ps.executeQuery (); // Proper printed for inspection of the results behind. While (rs.next ()) {system.out.println (rs.getstring ("name"));}} rs.beforefirst (); // You must use BeforeFirst, because RowSetDynaclass only scroll forward from the current location RowsetDynaclass RSDC = New RowSetdyNaclass (RS); rs.close (); ps.close (); list rows = rsdc.getrows (); // Returns a standard list, stored DynabeanFor (INT i = 0; i

3. The Dynabean returned by the resultSetiterator's next () method is actually pointing to a fixed object within its internal, and the internal value is changed after each time next (). The purpose of this is to save memory. If you need to save the Dynabean each time you build, you need to create another Dynabean and copy the data in the past. The following is the code in Java DOC: ArrayList Results = new arraylist (); // to hold copied list ResultSetDynaClass rsdc = ...; DynaProperty properties [] = rsdc.getDynaProperties (); BasicDynaClass bdc = new BasicDynaClass ( "foo", BasicDynaBean.class, rsdc.getDynaProperties ()); Iterator rows = rsdc.iterator () ; while (rows.hasNext ()) {DynaBean oldRow = (DynaBean) rows.next (); DynaBean newRow = bdc.newInstance (); PropertyUtils.copyProperties (newRow, oldRow); results.add (newRow);} fact Dynaclass / DynaBean can be used in many places to store various types of data. I think I think.嘿嘿. Nine, custom CustomrowSetDynaclass writes a class that is the same as the RowSetDynaclass target two years ago, but more features, it is paging, only required data, so memory usage will decrease.

First see a code: string driver = "com.mysql.jdbc.driver"; striver "; string url =" jdbc: mysql: // localhost / 2hu? Useunicode = true & characterencoding = GBK "; string username =" root "; string password =" "; java.sql.Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try {Class.forName (driver) .newInstance (); con = DriverManager.getConnection (url); ps = con.prepareStatement (" Select * from forumlist order by name "); rs = ps.executeQuery (); / * while (rs.next ()) {system.out.println (rs.getstring (" name ");}} rs.beforefirst ); * /// Second parameter representation Sequence, the third parameter representation page size CustomrowSetdynaclass RSDC = New CustomrowSetdyNaclass (RS, 2, 5); // RowSetDynaclass RSDC = New RowSetDynaclass (RS); rs.close (); ps.close (); list rows = rsdc.getrows (); for (int i = 0; i

The code of this class is as follows: package test.jakarta.commons.beanutils; import java.io. *; Import java.sql. *; Import java.util. *; Import org.apache.commons.beanutils. *; / ** * @author SonyMusic ** to change this generated comment edit the template variable "typecomment":. * Window> Preferences> Java> Templates * to enable and disable the creation of type comments go to * Window> Preferences> Java> Code Generation. * / Public class customer {// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ -------------------- CONSTRUCTORS / ***

Construct a new {@Link RowSetDynaclass} for the specified * ResultSet . The property names corresponding * to column names in the result set will be lower cased. ** @param resultSet The result set to be wrapped ** @exception NullPointerException if resultSet * is null * @Exception SQLEXCEPTION IF The Metadata for this Result set * cannot be introspected * / public customrowsetDynaclass (Resultset Resultset) throws Sqlexception {THI s (resultSet, true);.} / ***

Construct a new {@link RowSetDynaClass} for the specified * ResultSet The property names corresponding * to the column names in the result set will Be Lower Cased or Not, * Depending On The Specified Lowercase value. **

warning - if you specify false * for LowerCase

, The returned property names will * exactly match the column names returned by your JDBC driver. * Because different drivers might return column names in different * cases, the property names seen by your application will vary * depending on which JDBC driver you are using. ** @param resultSet The result set to be wrapped * @param lowerCase Should property names be lower cased? ** @exception NullPointerException if resultSet * is null * @exception SQLException if the metadata for this result set * can not be introspected * / public CustomRowSetDynaClass (ResultSet resultSet, boolean lowerCase) throws SQLException {this (resultSet, 1, -1, lowerCase);} public CustomRowSetDynaClass (ResultSet resultSet, int page , int pageSize, boolean lowerCase) throws SQLException {if (resultSet == null) {throw new NullPointerException ();} this.lowerCase = lowerCase; this.page = page; this.pageSize = pageSize; introspect (resultSet); copy ( } public customrowsetdynaclass (Resultset Resultset, INT page, INT PageSize) Throws Sqlexception {this (ResultSet, Page, PageSize, True);} // --------------------------- -------------------------- Instance variables / ***

flag defining WHETHER column names shouth be limited to copywhen * control . * / protected boilean lowercase = true; protected int page = 1; protected int page = -1; / ***

the set of dynamic prof.link dynaclass}. * / protected Dynaproperty Properties [] = null; / ***

The set of dynamic printerties That Are Part of this * {@

link DynaClass}, keyed by the property name Individual descriptor * instances will be the same instances as those in the * properties list * / protected Map propertiesMap = new HashMap ();.. / ***

the list of {@link dynabean} s representing the contents of * the original resultset on which this * {@link rowsetdynaclass} WAS Based. * / protected list Rows = new arraylist (); // ----------------------------------------- ------------- Dynaclass methods / ***

return the name of this Dynaclass (Analog to the * getName () method of Java. lang.Class DynaClass implementation class to support * different dynamic classes, with different sets of properties. * / public String getName () {return ( THIS.GETCLASS (). getname ());} / ***

return a property descriptor for the specified property, if it * exists; OtherWise, Return null . * * @Param Name Name of the Dynamic Property for Which a descriptor * is Req uested ** @exception IllegalArgumentException if no property name is specified * / public DynaProperty getDynaProperty (String name) {if (name == null) {throw new IllegalArgumentException ( "No property name specified");} return ((DynaProperty) propertiesMap. get (name));} / ***

Return an array of ProperyDescriptors for the properties * currently defined in this DynaClass If no properties are defined, a * zero-length array will be. Returned. * / public Dynaproperty [] getDynaproperties () {return (property);} / ***

Instantiate and return a new DynaBean instance, associated * with this DynaClass NOTE -. This operation is not * supported, and throws an exception ** @exception IllegalAccessException if the Class or the appropriate. * constructor is not accessible * @exception InstantiationException if this class represents an abstract * class, an array class, a primitive type, or void; or if instantiation * fails for some other reason * / public DynaBean newInstance () throws IllegalAccessException, InstantiationException { Throw new unsupportedOperationException ("newinstance () not supported");} // ------------------------------------------------------------------------------------------------------------ ----------------------- Public method Methods / ***

return a list containing the {@Link Dynabean} S that * represent the contents of each Row from the * ResultSet that was the basis of this * {@link RowSetDynaClass} instance. These {@link DynaBean} s are * disconnected From The Database Itself, So There Is No Problem with * Modifying the contents of the list, or the values ​​of the properties * of these {@link DynaBean} s. However, it is the application's * responsibility to persist any such changes back to the database, * if it so desires. * / public list getRows () {return (this.rows);} // -------------------------------- ---------------------- Protected methods / ***

Copy The Column Values ​​for Each Row in The Specified * ResultSet Into a newly created {@link dynabean}, and add * this bean to the list of {@link dynabean} s tria Will Later by * Returned by a call to getRows () . ** @

param resultSet The ResultSet whose data is to be * copied ** @exception SQLException if an error is encountered copying the data * / protected void copy (ResultSet resultSet) throws SQLException {int abs = 0; int rowsCount = 0; int currentpageROWS = 0; ResultSet.last (); rowscount = resultset.Getrow (); if (Pagesize! = -1) {INT TOTALPAGES = (int) Math.ceil ((Double) Rowscount) / pageSize IF (Page> Totalpages) Page = Totalpages; IF (Page - 1) * Pagesize; // CurrentPageRows = (Page == Totalpages? RowsCount-PageSize * (Totalpages-1) : pageSize);} elsepageSize = rowsCount; if (abs == 0) resultSet.beforeFirst (); elseresultSet.absolute (abs); // int while (resultSet.next () && currentPageRows <= pageSize) {DynaBean bean = New BasicDynabean (this); for (int i = 0; i Introspect the metadata associated with out set, and populate * the Properti es and propertiesMap instance * variables. ** @param resultSet The resultSet whose metadata is to * be introspected ** @exception SQLException if an error is encountered processing the * result set metadata * / protected void introspect (ResultSet resultSet) throws SQLException {// Accumulate an ordered list of DynaPropertiesArrayList list = new ArrayList (); ResultSetMetaData metadata = resultSet.getMetaData (); int n = metadata. getColumnCount (); for (int i = 1; i <= n; i

) {// JDBC is one-relative DynaProperty dynaProperty = createDynaProperty (metadata, i);! If (dynaProperty = null) {list.add (dynaProperty);!}} // Convert this list into the internal data structures we needproperties = (Dynaproperty []) List.Toarray (New Dynaproperty [list.size ()]); for (int i = 0; i factory method to create a new Dynaproperty for the Given Index * INTO The Result set metadata. * * @Param metadata is the result set metadata * @Param I is the column index in the metadata * @return the newly created DynaProperty instance * / protected DynaProperty createDynaProperty (ResultSetMetaData metadata, int i) throws SQLException {String name = null; if (lowerCase) {name = metadata.getColumnName (i) .toLowerCase ();} else {name = metadata.getColumnName (i);} String className = null; try {className = metadata.getColumnClassName (i);} catch (SQLException e) {// this is a patch for HsqlDb to ignore exceptions // thrown by its metadata implementation} // Default to Object type if no class name could be retrieved // from the metadataClass clazz = Object.class; if (className = null!) {clazz = loadClass (className);} return new DynaProperty ( Name, CLAZZ);} / ***

loads and returns the class of the given name. * by default, a loading from the thread context class logader is attempted. * if there is no Such Class Loader, The Class Loader Used To Load this * Class Will Be Utilized. ** @

转载请注明原文地址:https://www.9cbs.com/read-87394.html

New Post(0)