Author: Sonymusic 2003.05.13
Sixth, constructorutils supplement
There is also a method for creating an object: InvokeExactConstructor, the method requires parameter requirements
More stringent, the passing parameters must strictly meet the parameters of the constructor.
E.g:
Object [] args = {new integer (1), "jan"};
Class [] argstype = {INT.CLASS, STRING.CLASS}
Object obj;
// The call will not succeed, because the type of Args [0] is Integer, not 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);
Seven, MethodUtils
Similar to constructorutils, but when called, you typically need to specify a parameter of Method Name.
Eight, Dynaclass / Dynabean
This seems to be one of the most interesting parts in Beanutils, very simple, simple to look at these two interfaces in these two interfaces, do not understand
Why design these two interfaces. However, after seeing ResultSetDynaclass, I understand. Here is the code in Java DOC:
ResultSet RS = ...
ResultSetdyNaclass RSDC = New ResultSetDynaclass (RS);
Iterator rows = rsdc.iterator ();
While (rows.hasnext ()) {
Dynabean row = (Dynabean) rows.next ();
... Process this Row ...
}
Rs.close ();
It turns out that this is a RESULTSET wrapper, resultSetdyNaclass implements Dynaclass, and its Iterator method returns one
ResultSetiterator, the Dynabean interface is implemented.
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
Look at another type of RowSetDynaclass, 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 ();
// Print it first, used to check the results behind.
While (rs.next ()) {
System.out.println (rs.getstring ("name");
}
rs.beforefirst (); // 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 Dynabean
For (int i = 0; i Dynabean B = (Dynabean) Rows.get (i); System.out.println (B.Get ("Name"); } } catch (exception e) { E.PrintStackTrace (); } Finally { Try { C. close (); } catch (exception e) { } } Is it very interesting? Encapsulated the result of ResultSet, the cost is occupied memory. If a table has 100,000 records, rsdc.getrows () It will return 100,000 records. @ _ @ It should be noted that the difference between ResultSetdyNaclass and RowSetDynaclass: 1. ResultSetdyNaclass is based on Iterator, only one record is returned once, and RowSetDynaclass is based on List, one time returns all records. The direct impact is that the RESULTSETDYNACLASS will compare quickly in the data comparison. RowSetdyNaclass needs to read all the data in the Resultset (and stored inside), will take up too much Memory, and speed is slow. 2, ResultSetdyNaclass only processes a record at a time, and the resultSet cannot be turned off before processing is completed. 3. The Dynabean returned by the resultSetiterator's next () method is actually a fixed point to its internal Object, after each next (), the internal value will be changed. The purpose of this is to save memory if you need to save each The subsequent Dynabean needs 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 property [] = rsdc.getDynaproperties (); Basic Dynaclass BDC = New Basic Dynaclass ("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 (new); } In fact, Dynaclass / DynaBean can be used in many places to store various types of data. I think I think.嘿嘿. Nine, custom CustomrowSetDynaclass Two years ago, a class that is the same as the RowSetDynaclass target, but more features, it is paging, only the required data, This memory is reduced. First see a code: 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 order by name); RS = ps.executeQuery (); / * While (rs.next ()) { System.out.println (rs.getstring ("name"); } Rs.beforefirst (); * / // Second parameter represents the second page, the third parameter represents the size of the page 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 Dynabean B = (Dynabean) Rows.get (i); System.out.println (B.Get ("Name"); } } catch (exception e) { E.PrintStackTrace (); } Finally { Try { C. close (); } catch (exception e) { } } Here, there is a CustomrowSetDynaclass class, and two parameters of Page and PageSize are added to the constructor. In this way, only the number of records in the database is recorded, only the PageSize strip record is recorded, if PageSize == - 1, the function and RowsetDynaclass is the same. This is suitable in most cases. 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. * TOEABLE AND DISABLE The Creation of Type Comments Go to TO * Window> Preferences> Java> Code Generation. * / Public Class CustomrowSetDynaclass Implements Dynaclass, Serializable { / / -------------------------------------------------------------------------------------------- ----------- Constructionors / ** * construct a new {@link rowsetdynaclass} for the specified * * To column name in the result set will be lower cased. p> * * @Param Resultset The Result set to be wrappe * * @Exception nullpointersRexception if * IS * @Exception SQLEXCEPTION IF The Metadata for this Result Set * Cannot be introspected * / Public CustomrowSetDynaclass (Resultset Resultset) throws Sqlexception { This (resultSet, true); } / ** * construct a new {@link rowsetdynaclass} for the specified * * To the column name in the result set will be lower canceled or not, * Depending on the specified * * Warning strong> - if you specify * for * 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 use. p> * * @Param Resultset The Result set to be wrappe * @PARAM LOWERCASE SHOLD PROPERTY NAMES BE LOWER CASED? * * @Exception nullpointersRexception if * IS * @Exception SQLEXCEPTION IF The Metadata for this Result Set * Cannot 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 nullpointerserException (); } this.Lowercase = LowerCase; THIS.PAGE = Page; THIS.PAGESIZE = Pagesize; Introspect (ResultSet); Copy (ResultSet); } Public CustomrowSetDynaclass (Resultset Resultset, Int page, int pageSize) Throws sqlexception { This (ResultSet, Page, PageSize, True); } / / -------------------------------------------------------------------------------------------- ----- Instance Variables / ** * flag defining WHETHER column names shop be lower case * Converted to Property Names. p> * / Protected Boolean Lowercase = True; protected int point = 1; Protected int Pagesize = -1; / ** * The set of dynamic printies That Are Part of this * {@link dynaclass}. p> * / Protected Dynaproperty Properties [] = NULL; / ** * The set of dynamic printies That Are Part of this * {@link dynaclass}, keyed by the property name. Individual Descriptor * Instances Will Be The Same Instances As Those in The * * / Protected Map PropertiesMap = new hashmap (); / ** * the list of {@link dynabean} s representing the contents of * The Original * {@Link RowSetDynaclass} WAS Based. p> * / Protected List rows = new arraylist (); / / -------------------------------------------------------------------------------------------- ------ DYNACLASS METHODS / ** * return the name of this Dynaclass (Analog to the * * Allows the Same * DiffERENT DYNAMIC CLASSES, WITH DIFFERENT SETS OF Properties. P> * / Public string getname () { Return (this.getclass (). getname ()); } / ** * return a property descriptor for the specified property, if IT * EXISTS; OtherWise, Return * * @Param Name Name of the Dynamic Property for Which A Descriptor * Is Requester * * @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 * Currently Defined in this Dynaclass. if no property it defined, A * Zero-Length Array Will Be Returned. P> * / Public Dynaproperty [] getDynaproperties () { Return (Properties); } / ** * instantiate and return a new Dynabean Instance, Associated * with this Dynaclass. Note strong> - this Operation is Not * Supported, and throws an exception. p> * * @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 IllegaCcessException, InstantiationException { Throw new unsupportedOperationException ("NewInstance () Not supported; } / / -------------------------------------------------------------------------------------------- --------- Public Methods / ** * return a * Repesent the contents of each * * {@link rowsetdynaclass} instance. these {@Link Dynabean} S Are * Disconnected from the Database Itself, So There is no problem * Modifying the contents of the list, or the value of the profmenties * of these {@link dynabean} s. however, it is the application. * Responsibility to persist Any Such Changes Back to the Database, * if it so desires. p> * / Public List getRows () { Return (this.Rows); } / / -------------------------------------------------------------------------------------------- ------ Protected Methods / ** * Copy the column value for each row in the specified * * this bean to the list of {@Link Dynabean} S That Will Later by * Returned by a call to * @Param ResultSet the * 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) Page = 1; ABS = (PAGE - 1) * Pagesize; // CurrentPagerows = (Page == Totalpages? RowsCount-Pagesize * (Totalpages-1): pagesize Else PageSize = rowscount; IF (ABS == 0) ResultSet.beforefirst (); Else ResultSet.Absolute (ABS); // int While (ResultSet.Next () && currentpagerows <= pagesize) { Dynabean bean = new basicdynabean (this) For (INT i = 0; i String name = proties [i] .GetName (); Bean.set (name, resultset.getObject (name); } Rows.Add (bean); } } / ** * Introspect the metadata associated with our results, and populate * The * Variables. p> * * @Param Resultset The * 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 Dynaproperties ArrayList 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 NEED PROPERTIES = (Dynaproperty []) List.toArray (New Dynaproperty [list.size ()]); For (INT i = 0; i PropertiesMap.Put (Properties [i] .getname (), Properties [i]); } } / ** * factory method to create a new Dynaproperty for the Given Index * INTO The Result set metadata. p> * * @Param metadata is the result set metadata * @Param I is the column index in the metadata * @Return the newly create 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 ustementation } // default to object Type if no class name could be retrieved // from the metadata Class Clazz = Object.class; IF (classname! = null) { Clazz = loadingClass (classname); } Return New Dynaproperty (Name, Clazz); } / ** * loads and returns the * By Default, a loading from the thread context class logader is attempted. * If there is no self. loading * Class Will Be utilized. p> * * @Exception SQLEXCEPTION IF An Exception Was Thrown Trying to Load * The Specified Class * / Protected class loadclass (string classname) throws sqlexception { Try { ClassLoader Cl = Thread.currentthread (). GetContextClassLoader (); IF (CL == NULL) { CL = this.getClass (). getClassLoader (); } Return (Cl.LoadClass (ClassName); } catch (exception e) { Throw new sqlexception "Cannot Load Column Class '" ClassName "':" E); } } } Most of the code takes only a simple modification from the source code of BeanUtils, and there is no additional comments. If you want to use it, Need to do finishing. ========================================= Regarding this package, I am ready to test here, but I have a probably impression, at least, know what this package can do. In fact, this note has only played this role. @ _ @ ResultSet code>. The property names Corresponding
ResultSet code>
null code>
ResultSet code>. The property names Corresponding
Lowercase code> value. p>
false code>
LowerCase code>, The Returned Property Names Will
ResultSet code>
null code>
Properties code> list. p>
ResultSet code> on Which THIS
getname () code> method of
java.lang.class code), Which
Dynaclass code> Implementation Class To Support
NULL code>. p>
ProPERYDESCRIPTORS CODE> for the Properties
list code> containing the {@link dynabean} s
ROW code> from the
ResultSet code> That Was the Basis of this
resultset code> INTO A newly created {@link dynabean}, and add
getRows () code>. p> *
ResultSet code> whose data is to be
Properties code> and
PropertiesMap code> instance
ResultSet code> whose metadata is to
class code> of the given name.