Field What is it?
a class field is located next java.lang.reflect package. Java class field in reflection is described in the attribute information of the class include:
1: Get the type of the current object member variables
2: Reset the value of the member variable
How to use the field it?
Four ways to get to class object field
1: Class.getFields () Get the type of the class of public property, some field returns an array containing objects, the array contains the class or interface represented by this Class object of all the accessible public fields
2: getDeclaredFields () Gets all class attributes (public protect default private), but does not include inherited attributes, the object returns an array of field
3: getField (String name) acquires class-specific methods, name parameter specifies the name of the property
4: getDeclaredField (String name) acquires class-specific methods, name parameter specifies the name of the property
Field object common methods
Gets the type of a variable
Field.getType (): Returns the type of the variable
Field.getGenericType: If the current property returns a signed property type, otherwise return Field.getType ()
isEnumConstant (): This attribute determines whether the enumeration class
Gets a member variable modifiers
java language modifiers Field.getModifiers () Returns the integer Field object identified in field
Access and modify the values of member variables
getName (): Gets the name of the property
get (Object obj): Returns the field value specified in this field indicates the object obj
set (Object obj, Object value) set a field on the object variable This field specifies the object represented by the new value for the specified
Common Errors
When set (Object obj, Object value), the type of the original value and the new value will lead to inconsistencies when the reflection type conversion exception [obtain or modify the value of a variable, the compiler will not automatically detachable box, some types require their conversion manually]
When set (Object obj, Object value), modify the final type of variable type conversion abnormality caused. Due Field inherited from AccessibleObject, we can use AccessibleObject.setAccessible () method tells the security mechanism, the variables can be accessed
It can be solved, such as field.setAccessible (true).
getField (String name) or getField () to obtain non-public variables, the compiler will report the wrong java.lang.NoSuchFieldException