The job encountered a requirement to update the Java object based on the return JSON. Read the data, wrote a tool class, and learned that reflection gets the set generic type. The JSON class library in the code is Fastjson
1 Public classJsonutil {2 3 /**4 * JavaBean properties are more than JSON, updating JavaBean the same name field values based on JSON5 *6 * @paramBean7 * @paramJSON8 * @param<T>9 */Ten Public Static<T>voidPatchupdate (T Bean, jsonobject JSON)throwsException { Oneset<string> keys =Json.keyset (); Afield[] Fields =Bean.getclass (). Getdeclaredfields (); - for(String key:keys) { - for(Field field:fields) { the if(Field.getname (). Equals (key)) { -String value =json.getstring (key); -String type =Field.gettype (). toString (); -Field.setaccessible (true); + if(Type.endswith ("String")) { - Field.set (bean, value); +}Else if(Type.endswith ("int")) { A Field.set (Bean, Integer.parseint (value)); at}Else if(Type.endswith ("Double")) { - Field.set (Bean, double.parsedouble (value)); -}Else if(Type.endswith ("Date")) { -DateFormat Fmtdatetime =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); -Date Date =Fmtdatetime.parse (value); - Field.set (bean, date); in}Else if(Type.endswith ("List")) { - //gets the type of List first:java.util.list<e> toParameterizedtype pt =(Parameterizedtype) Field.getgenerictype (); + //Get generics: E -Class E = (Class) pt.getactualtypearguments () [0]; theList List =Jsonarray.parsearray (value, e); * field.set (bean, list); $ }Panax Notoginseng } - } the } + } A}
To partially update the properties of a javabean by using reflection to implement JSON data