Java obtains the object property type, attribute name, and attribute value.

Source: Internet
Author: User

Because the project needs to be used, some common operations are encapsulated:

/*** Get Attribute Value Based on attribute name **/private object getfieldvaluebyname (string fieldname, object O) {try {string firstletter = fieldname. substring (0, 1 ). touppercase (); string getter = "get" + firstletter + fieldname. substring (1); Method method = O. getclass (). getmethod (getter, new class [] {}); object value = method. invoke (O, new object [] {}); return value;} catch (exception e) {log. error (E. getmessage (), e); return NULL ;}/ *** get attribute name array **/private string [] getfiledname (Object O) {field [] fields = O. getclass (). getdeclaredfields (); string [] fieldnames = new string [fields. length]; for (INT I = 0; I <fields. length; I ++) {system. out. println (fields [I]. getType (); fieldnames [I] = Fields [I]. getname ();} return fieldnames;}/*** get the type, name, and value) list **/private list getfiledsinfo (Object O) {field [] fields = O. getclass (). getdeclaredfields (); string [] fieldnames = new string [fields. length]; List list = new arraylist (); map infomap = NULL; For (INT I = 0; I <fields. length; I ++) {infomap = new hashmap (); infomap. put ("type", fields [I]. getType (). tostring (); infomap. put ("name", fields [I]. getname (); infomap. put ("value", getfieldvaluebyname (fields [I]. getname (), O); list. add (infomap);} return list;}/*** get all attribute values of an object and return an array of objects **/public object [] getfiledvalues (Object O) {string [] fieldnames = This. getfiledname (o); object [] value = new object [fieldnames. length]; for (INT I = 0; I <fieldnames. length; I ++) {value [I] = This. getfieldvaluebyname (fieldnames [I], O);} return value ;}

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.