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 );
}
}