Java traversal class field attributes and Field Values, java Fields

Source: Internet
Author: User

Java traversal class field attributes and Field Values, java Fields

Public class ReflectUtil {

Public static void reflect (Object o ){
// Obtain the parameter class
Class cls = o. getClass ();
// Convert the parameter class to an array of the Field type corresponding to the number of attributes (that is, the length of the converted array after the number of attribute fields N in this class is N)
Field [] fields = cls. getDeclaredFields ();
For (int I = 0; I <fields. length; I ++ ){
Field f = fields [I];
F. setAccessible (true );
Try {
// F. getName () get the attribute name of the corresponding field, f. get (o) get the attribute value of the corresponding field, f. getGenericType () get the type of the corresponding field
System. out. println ("attribute name:" + f. getName () + "; property value:" + f. get (o) + "; field type:" + f. getGenericType ());
} Catch (IllegalArgumentException | IllegalAccessException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}
Public static void main (String [] args ){
Student s = new Student ();
S. setName ("James ");
S. setAge (12 );
S. setGrade (89 );
Reflect (s );
}
}

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.