origin
In JDBC applications, we often need a JavaBean: When we take the value from the database, we hope to assure the corresponding value to the JavaBean, then manipulate the JavaBean for various business processing; and we save the data I also want to assign the value after the business processed to Javabean, and then interact with JavaBean with JDBC, save the data in the database.
In Struts applications, we often have to deal with ActionForm or DynaActionform, such as the data acquired by the user, in the Struts application, we actually get data from the ActionForm; when the data is displayed to the user, we actually The data is assigned to the ActionForm. In actual applications, we often have an intermediate JavaBean, which is used to deal with ActionForm, which is values, assignment.
The above two applications require an intermediate JavaBean, acquire data from the data source, assigning JavaBean; then manipulates the processing of business logic; finally, the data is given to the data source from JavaBean.
This has the following assignment process:
STMT = ("{call ft_save_fabric.ft_fab_save_fabric.ft_fab_colorway_general_insert (" "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? ,?,?,?,?)} ");
Stmt.setlong (1, Fabric.GetBom_ID ());
Stmt.setlong (2, general.getColorway_Number ());
Stmt.setlong (3, general.getcolor_number ());
Stmt.setfloat (4, general.getColorway_type_id ());
Stmt.setstring (5, general.getprint_id ());
Stmt.setstring (6, general.getprint_name ());
Stmt.setfloat (7, general.getprint_type_id ());
Stmt.setfloat (8, general.getprint_repeat_type_id ());
Stmt.setfloat (9, general.getprint_repeat_height ());
Stmt.setlong (10, General.getPrint_repeat_height_uom_id ());
Stmt.setfloat (11, General.getPrint_repeat_width ());
Stmt.setlong (12, general.getprint_repeat_width_uom_id ());
Stmt.setlong (13, general.getprint_status_id ());
Stmt.setstring (14, general.getyarn_dye_id ());
Stmt.setstring (15, general.getyarn_dye_name ());
Stmt.setint (16, general.getyarn_wrap_color_number ());
Stmt.setint (17, general.getyarn_weft_color_number ());
Stmt.setfloat (18, general.getyarn_repeat_height ());
Stmt.setlong (19, general.getyarn_repeat_height_uom_id ()); stmt.setfloat (20, general.getyarn_repeat_width ());
Stmt.setlong (21, general.getyarn_repeat_width_uom_id ());
Stmt.setlong (22, general.getyarn_status_id ());
Stmt.setlong (23, General.getPrint_Process_ID ());
Stmt.execute ();
Example
The above is about the assignment code segment for JDBC, let us look at an example:
Public Int setfabricWebBasData (DynaActionform Form, HttpservletRequest Request, Le_fabricbean bean) {
Bean.setfabric_no ((string) form.get ("txtid");
Bean.setbarcode_id (String) Form.Get ("txtbarcodeid");
Bean.setstatus_id (TransformTools.GetObjectInt)))))))))))); "DDLSTATUS"))
Bean.setMaterial_type_id (TransformTools.GetObject)))))));
Bean.setfabric_type_id (TRANSFORTOOLS.GETOBJECTINT ((String) Form.Get ("DDLFABRICTYPE"))
Bean.setfabric_end_use_id (TransformTools.GetObject)))))))))); 00.s.G ("Ddlenduse)))
Bean.setvendor_Number (String) Form.Get ("txtarticle"));
Bean.setRegion_ID (TransformTools.GetObjectInt)))))));
Bean.setCountry_ID (TransformTools.GetObjectInt ((String) Form.Get ("DDLCOUNTRY")))
Bean.setColor_Range_ID (TransformTools.GetObject))));
Bean.setPattern_ID (TransformTools.GetObjectInt ")))))))));
System.out.println ("=================================>" Form.Get ("txtcomments"));
Bean.setdescription ((string) form.get ("txtdescription");
Bean.setdetail (String) Form.Get ("txtcomments");
Bean.setformset_id (TransformTools.GetObjectString ("HidFormSetID"))))); libImageManage.setimageData (Request, Bean);
Return 0;
}
Example
Obviously, this example is the assignment between ActionForm and JavaBean.
From the above two examples, we can see that in JDBC, or Struts, the assignment between JavaBean and ActionForm is very cumbersome, also brings a lot of code redundancy; especially in an actual In the application of the B / S architecture, we often use the Struts JDBC development model, which has a large number of JavaBean to rebound between the JDBC and the data sources, and the comingback between JavaBean and Actionform assigns a value, the two add together The redundancy of the code is greatly amazing. For programmers, such assignment is determined, it is indeed boring.
Such a lengthy code, I look at it, I found the structure of the actual code, all of which value the value from an object, and then go to another object. In this way, my first idea is to be a public method, then we will conduct for loop call. Going down, I am dumbfounded, because no matter which class value or assignment, their methods are not the same, as examples, there are both stmt.setstring, and stmt.setlong. In this way, we extract a public approach with a conventional method.
Analysis of this, I feel a feeling that enters the dead alley. But no matter what, I can determine that the way is to draw a common method, then call the method through the for loop. It can be determined that the problem is how to construct this public method.
For this public method, we have the object, the method of the object, the parameters of the method, and we need to call the method. It is clear that some methods are called in the run. In this way, we have the bottom, and Java reflex mechanism can solve this problem.
Review of the reflection mechanism
Now let's review the Java reflex mechanism:
The reason why it is a piece of break, because we don't intend to show the entire Java reflex mechanism here, this is not the purpose of this article. The purpose of this article is to let readers who have learned Java reflex mechanisms or readers who have not learned Java reflex mechanisms to see an example of Java reflex mechanism in practical application; for readers who have not learned Java reflex mechanisms, through this article, know The Java reflex mechanism is used in the actual application, increasing the enthusiasm of the reader to learn the Java reflex mechanism, thereby further studying the Java reflex mechanism; for readers who have already learned Java reflex mechanism, you can pass this article, see Java reflex mechanism What is applied in practice, further understanding Java reflection, this point I deeply experienced that I didn't understand it for a long time after I learned Java reflections, and I didn't know how to use it in actual use. To it.
If the reader wants to learn the Java reflex mechanism, you can use the reference article listed herein. These articles are used when I have learned the Java reflex mechanism. It can be said to have some representative.
In a sentence, the Java reflection mechanism to be described herein is the Java reflex mechanism to be used herein. When reading the solution to the problem of this article, the reader may wish to combine the solution to the actual problem and the Java reflection mechanism I will declare to increase the understanding of the Java reflex mechanism.
Ok, gossip less, let's take a look at the Java reflex mechanism to use in this article:
1. Class object of the object
Each object has a getClass () method that can get the Class object of the object. The code for obtaining the Class object of the object O is as follows:
Class C = O.getClass ();
2. Object's properties
The Java reflective mechanism can dig the metadata of the object itself, such as the parent class of the object, the object of the object, the method of the object, and the like. Here we take a look at how the Java reflex mechanism gets the properties of the object.
With an object's Class object, we can use the getDeclaredfields () method to get all the properties of this object; we can also get this property through the attribute name of a attribute, the method is: getDeclaredfield (String FieldName). For example, we want to get a name attribute in the O object, the code is as follows:
Class C = O.getClass ();
Field f = C.GetDeclaredField ("name");
With property objects, we can further get information about this property. Such as the model of the properties, the type of attribute, and so on. Let's take a look at how to get the property, the code is as follows:
Class T = f.gettype ();
In this way, we can get attribute type names:
String typeName = T.GETNAME ();
3. Method for acquiring objects
The properties of the object are obtained above, and we can also obtain the method of the object and the metadata of the method, such as the scope of the method, input parameters, return value type, etc.
getDeclaredMethod (String FunctionName, Class [] Types)
The method has two input parameters, the first is functionName, let's take a look at the method name of the method we need to get; the second parameter Types is an array object of a class type, which is the input we need to get the input. Class arrays consisting of parameters.
For example, we want to get a method of using the public string function of the O object.
First we know how the method is named: "FUNC"
Let's construct the second input parameter for the getDeclaredMethod method:
Class ptypes [] = new class [2];
Ptypes [0] = Class.Forname ("java.lang.string");
Ptypes [1] = Class.Forname ("java.util.hashtable);
In this way, we can get this method:
Method M = C.getMethod ("FUNC", PTYPES);
4. Method of calling an object during operation
It can be said that the method of calling an object during operation is the core of the Java reflex mechanism.
The method of calling an object during the running period, including the scheduler of the scheduler, that is, an instance of the class within the runtime, which is also very useful in the actual application of Java reflex mechanism. However, the example in this article is not used, therefore no longer states, interested readers can learn from the references later in this article.
Here you focus on the ordinary way to call the object during the running period
INVOKE (Object O, Object [] args)
The method also has two input parameters: one is an object object, which is the object we need to call during the running period, as the O object mentioned above; the second parameter is an array composed of Object objects, Refers to the actual input parameters of the method we need to call during the run. If the input parameter is "Hello, World!" And NULL, we want to call the O object's public string func (String S, HashTable HT) such a method, the regular call mode is:
String s = o.func ("Hello, World!", NULL;
We apply Java reflex mechanism to call within the run period:
Object args [] = new object [2];
Arg [0] = New String ("Hello, World");
Arg [1] = NULL;
Object r = m.invoke (OBJ, ARG);
String s = (string) r;
Among them, the object M has been obtained by the previous Java reflection mechanism.
Here, the Java reflex mechanism to be used herein has been fully stated. It can be seen that this article is not a lot about the knowledge point of Java reflex mechanism, but the Java reflection mechanism has such a cow knife trial, which makes our code have been optimized, and it can be seen that Java reflex mechanism is indeed.
Solution
We first look at the process of processing examples:
Through the previous analysis, we can concatenation, we need such a public method: in this method, the input parameters we can provide are:
One. STMT is used to get the value of the field in Table.
two. In the database table, we have to get the location of the field, such as from 1 to 23 from 1 to 23, we can construct an INT type: int [] ports = new int = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23};
three. Object of Javabean, in Example: General
four. A JavaBean's attribute name consists of an array, with a one in front of the field position. In one of the cases: String [] propNames = new String [] { "bom_id", "colorway_number", "color_number", "colorway_type_id", "print_id", "print_name", "print_type_id", "print_repeat_type_id", "print_repeat_height "," print_repeat_height_uom_id "," print_repeat_width "," print_repeat_width_uom_id "," print_status_id "," yarn_dye_id "," yarn_dye_name "," yarn_wrap_color_number "," yarn_weft_color_number "," yarn_repeat_height "," yarn_repeat_height_uom_id "," yarn_repeat_width "," yarn_repeat_width_uom_id ", "YARN_STATUS_ID", "Print_Process_ID"}; It can be seen that these attribute names are the name of the attribute corresponding to the javabean setxxx () method.
With the above four input parameters, we want to call such a public method, and the value of the fields in the STMT will be in the corresponding properties in the JavaBean. A common method for constructing as follows:
Public static void stmttobean (string "propnames, object o, int [] ports, oracle.jdbc.raclectatement Stmt)
In this method, we must first make a loop; in the cyclic body, we first take the value from the STMT; then assign the JavaBean object O.
Let's take a look at the actual code:
Public static void stmttobean (string [] PropNames, Object O, Int [] ports, OracleCallablestatement Stmt) throws valueManageRexception
{
// First we determine if the attribute name group is corresponding to the field location, if it is not throwing a violation.
IF (PropNames.Length! = Ports.Length)
{
System.out.println ("INPUT ARGS WRON: THE PROPNAMES 'LENGTH IS NOT The Same with The Ports' Length!");
Throw New ValueManageRexception ("INPUT ARGS WRONG: The PropNames 'Length Is Not The Same with The Ports' Length!");
}
Try
{
/ / Cycle the attribute name group
For (int i = 0; I { / / In the following statement, we first get the attribute name propNames [i]; then obtain its Class object in the JavaBean object O, O.GetClass (); finally obtains the attribute corresponding to the attribute name by the Class object. Field f = o.getClass (). GetDeclaredfield (PropNames [i]) // We take the name of the type corresponding to this property through attributes. String type = f.gettype (). Getname (); // The following statement is the focus, we make a tag, which is described later. ValueSetter.Valuetobean (Type, Tools.getSettername (PropNames [i]), O, Valuegetter.getStmtValue (Type, Ports [i], STMT); statement } } Catch (Exception E) { E.PrintStackTrace (); } In the above statement one, Let's see the input parameters of the valuetobe method: The first parameter, TYPE is the type of the attribute we have earned in front; The second parameter, there is a getSettername method, apparently wants to get the set method corresponding to the attribute name, let's see the GetSettername method in the Tools class. Public Static String GetSettername (String PropName) { Return "SET" PropName.Substring (0, 1) .touppercase () PropName.Substring (1, PropName.length ()); } It can be seen that the method is indeed obtained by the attribute name. The third parameter, o is a corresponding JavaBean object; the fourth parameter, there is a getStmtValue method, you can see that the method is to get the value of the corresponding position in the STMT, let's see the implementation of the getStmtValue method in the Valuegetter class: Public Static String GetStmtValue (String Type, Int Port, OracleCallablestatement Stmt) { Try { IF ("java.lang.string")))) { Return stmt.getstring (port); } Else if (Type.Equals ("int")) { Return String.Valueof (stmt.getint (port)); } Else IF (Type.equals ("long")) { Return String.Valueof (stmt.getlong (port)); } Else IF (Type.equals ("float")) { Return String.Valueof (stmt.getfloat (port)); } Else { System.out.println ("No Such Type!"); Return NULL; } } Catch (Exception E) { E.PrintStackTrace (); Return NULL; } } Sure enough, the value of the corresponding position is obtained from the STMT. Note: The reader can see that several types listed in this method are obviously not enough, and the reader can add the value of other types. Finally, let's take a look at the valuetobean method of the ValueSetter class. We can analyze that the functionality of the method is to assign the value obtained from the data source STMT to the field corresponding to the JavaBean object. The implementation of Valuetobean is as follows: Public Static void Valuetobean (String Type, String MethodName, Object O, String Value) { Try { IF (Tools.ISBLANK (S) &&! ("String")))). // First, it is still a Class object corresponding to the O object. Class C = O.getClass (); // For the following two statements, we also tagged in later statements. Class [] Types = Tools.gettypes (Type); statement Object [] args = Tools.getargs (Type, Value); statement // Get JavaBean method objects. Method M = C.getMethod (MethodName, Types); // Call the method. M.INVoke (O, ARGS); } Catch (Exception E) { E.PrintStackTrace (); } } Let's see the statement 2: It is obviously a Class array for constructing parameter types. Since there is only one parameter in the JavaBean, the type of parameter is named, so Tools.gettypes (Type) only has a parameter type TYPE requires construction, and the GetTypes method is implemented as follows: Public static class [] gettypes (String Type) { IF ("java.lang.string")))) { Return new class [] {string.class}; Else if (Type.Equals ("int")) { Return new class [] {integer.type}; } Else IF (Type.equals ("long")) { Return new class [] {long.type}; } Else IF (Type.equals ("float")) { Return new class [] {float.type}; } Else { System.out.println ("No Such Type!"); Return NULL; } } In this method, the same reader can be supplemented. The statement three is an array of object types of input parameter values according to the needs of the Invoke method. The implementation of Getargs is as follows: Public static object [] getargs (String Type, String Value) { IF ("java.lang.string")))) { Return New Object [] {new string (value)}; } Else if (Type.Equals ("int")) { Return New Object [] {new integer (integer.parseint (value))} } Else IF (Type.equals ("long")) { Return new object [] {new long (long.parselong (value))} } Else IF (Type.equals ("float")) { Return new object [] {new float (float.parsefloat (value))} } Else { System.out.println ("No Such Type!"); Return NULL; } } The above we have analyzed the solution to the solution of one issue. Now let's see the code implementation of calling this shared method: STMT = ("{call ft_save_fabric.ft_fab_save_fabric.ft_fab_colorway_general_insert (" "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? ,?,?,?,?)} "); Int [] ports = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}; String [] propNames = new String [] { "bom_id", "colorway_number", "color_number", "colorway_type_id", "print_id", "print_name", "print_type_id", "print_repeat_type_id", "print_repeat_height", "print_repeat_height_uom_id", "print_repeat_width", "print_repeat_width_uom_id", "print_status_id", "yarn_dye_id", "yarn_dye_name", "yarn_wrap_color_number", "yarn_weft_color_number", "yarn_repeat_height", "yarn_repeat_height_uom_id", "yarn_repeat_width", "yarn_repeat_width_uom_id", "yarn_status_id", "print_process_id "}; ValueManager. Stmttobean (propNames, General, Ports, STMT); Stmt.execute (); Similarly, we are implemented in the implementation of the mutual method of calling: Public Int setfabricWebBasData (DynaActionform Form, HttpservletRequest Request, Le_fabricbean bean) { String [] propNames = new String [] { "fabric_no", "barcode_id", "status_id", "material_type_id", "fabric_type_id", "fabric_end_use_id", "vendor_number", "region_id", "country_id", "color_range_id", "Pattern_ID", "Detail", "FormSet_ID"} String [] FieldNames = New String [] {"TXTID", "TXTBARCODEID", "DDLSTATUS", "DDLMATERIALTYPE", "DDLFABRICTYPE", "DDLENDUSE", "TXTArticle", "DDLREGION", "DDLCOUNTRY", "DDLCOLORRANGE", "DDLPATERN", "TXTDESCRIPTION", "TXTComments", "HIDFORMSETID"} ValueManager.formTobean (PropNames, Bean, FieldNames, Form); LibImageManage.setimagedata (Request, Bean); Return 0; } With regard to common methods, formtobean (String [] PropNames, Object O, String [] FieldNames, DynaActionform Form, and we can find them in the code of the appendix, and no longer state it here. Later At this point, we have run Java reflex mechanism to solve some of the cumbersome assignments in JDBC and Struts applications. It can be seen that the application of Java reflection mechanisms can indeed make the program code more flexible and convenient. It is for this reason that the Java reflex mechanism is widely used in the core code of an application. In many cases, we need to know the metadata of the class entered by the customer, call the class method during the run, instantiate a class during the run period, and so on need to use the Java reflex mechanism; Combining the Java reflex mechanism will be more flexible; Java reflection mechanisms and proxy models combine to form dynamic proxy models. In a word, the Java reflex mechanism makes our code more flexible and convenient, and the application is wide. references 1. Houjie point - Java reflex mechanism http://editblog.9cbs.net/programmer/archive/2004/10/27/806.aspx 2. Java programming dynamics http://www-900.ibm.com/developerWorks/cn/java/j-dyn0429/index.shtml 3. Java Reflection (Java Reflection) http://dev.9cbs.net/Article/58/58798.shtm appendix