Java object to map solution __java

Source: Internet
Author: User

Java object to map, which starts with Beanutils.describe (OBJ) in Org.apache.commons.beanutils.BeanUtils, which is for pure conversion of an object. There seems to be nothing unusual. When you put the converted map into the list of lists, you will find that the elements in the list are all the same. , debug for a long time, to confirm the implementation of the Add (map) method of the list, the map object is different, but when more than 2 maps are placed in the list, the elements inside are all turned into the last map element, which is strange and unexplained for a while.

the way to correct the back is to use the method of reflection. The specific functions are as follows:

private static map<string, string> obj2map (Object obj) {map<string, string> Map = new Ha
		Shmap<string, string> ();
		System.out.println (Obj.getclass ());
		Gets all the property fields in the corresponding class of the F object field[] fields = Obj.getclass (). Getdeclaredfields ();
			for (int i = 0, len = fields.length i < len; i++) {String varName = Fields[i].getname (); VarName = Varname.tolowercase ()//Set key to lowercase, default to object's property try {//Get original Access Control permission Boolean Accessflag = Fields[i].isacces
				Sible ();
				Modify access Control permission fields[i].setaccessible (true);
				Gets the variable object o = Fields[i].get (obj) in the object corresponding to the attribute fields[i in Object F;
				if (o!= null) map.put (VarName, o.tostring ());
				System.out.println ("The incoming object contains a variable as follows:" + varName + "=" + O);
			Restore access control permissions fields[i].setaccessible (Accessflag);
			catch (IllegalArgumentException ex) {ex.printstacktrace ();
			catch (Illegalaccessexception ex) {ex.printstacktrace ();
	} return map; }
Use this method to solve the problem perfectly, as you know beanutilsWhy would there be that problem, please do not hesitate to enlighten me

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.