Recently in the project with MyBatis, encountered the date format display to the Easyui problem, need to list<map<string, object>> into List<javabean> Finally found a method on the Internet:
The core approach is as follows:
[Java]View PlainCopy
- /**
- * object>> data is converted to JavaBean data according to List<map<string
- * @param datas
- * @param beanclass
- * @return
- * @throws commonexception
- */
- Public list<t> Listmap2javabean (list<map<string, object>> datas, class<t> beanClass) Throws Commonexception {
- //Return data collection
- list<t> list = null;
- //Object field name
- String fieldname = "";
- //object method name
- String methodname = "";
- //Object methods need to assign values
- Object Methodsetvalue = "";
- try {
- List = new arraylist<t> ();
- //Get all fields of the object
- Field fields[] = Beanclass.getdeclaredfields ();
- //Traverse data
- for (map<string, object> mapdata:datas) {
- //Create a generic type instance
- T t = beanclass.newinstance ();
- //Traverse all fields, corresponding to the configured fields and assign values
- For (Field field:fields) {
- //Get annotation configuration
- JavaBean JavaBean = field.getannotation (JavaBean. Class);
- if (null! = JavaBean) { //has annotation configuration, next action
- //Convert all to uppercase
- String dbfieldname = Javabean.dbfieldname (). toUpperCase ();
- //Get field name
- FieldName = Field.getname ();
- //Splicing Set method
- MethodName = "Set" + strutil.capitalize (fieldname);
- //Get the corresponding value in data
- Methodsetvalue = Mapdata.get (dbfieldname);
- //Assign To field
- Method m = Beanclass.getdeclaredmethod (methodname, Field.gettype ());
- M.invoke (t, Methodsetvalue);
- }
- }
- //Deposit back to list
- List.add (t);
- }
- } catch (Instantiationexception e) {
- throw New Commonexception (E, "Create Beanclass instance exception");
- } catch (Illegalaccessexception e) {
- throw New Commonexception (E, "Create Beanclass instance exception");
- } catch (SecurityException e) {
- throw New Commonexception (E, "get [" + FieldName + "] Getter Setter Method Exception");
- } catch (Nosuchmethodexception e) {
- throw New Commonexception (E, "get [" + FieldName + "] Getter Setter Method Exception");
- } catch (IllegalArgumentException e) {
- throw New Commonexception (E, "[" + methodname + "] Method Assignment Exception");
- } catch (InvocationTargetException e) {
- throw New Commonexception (E, "[" + methodname + "] Method Assignment Exception");
- }
- //Return
- return list;
- }
Using Java reflection mechanism to realize list<map<string, object>> conversion to list<javabean>