public static voidsetAccessible(AccessibleObject[] array,
boolean flag)
A convenience method that sets the accessible flag for an array of objects. If
setting the flag of an object throws a SecurityException only objects
earlier in the array will have their flags set to the given value, and all other
objects are unchanged.
public booleanisAccessible()
Returns the current value of the accessible flag for this object.
16.6. The Field Class
The Field class defines methods for asking the type of a field and for setting and getting the value of the
field. Combined with the inherited Member methods, this allows you to find out everything about the field
declaration and to manipulate the field of a specific object or class.
The getGenericType method returns the instance of Type that represents the field's declared type. For a
plain type, such as String or int, this returns the associated Class objectString.class and
int.class, respectively. For a parameterized type like List
ParameterizedType instance. For a type variable like T, it will return a TypeVariable instance.
The getType legacy method returns the Class object for the type of the field. For plain types this acts the
same as getGenericType. If the field's declared type is a parameterized type, then getType will return
the class object for the erasure of the parameterized typethat is, the class object for the raw type. For example,
for a field declared as List
type variable, then getType will return the class object for the erasure of the type variable. For example,
given class Foo
declared as Foo
You can ask whether a field is an enum constant using isEnumConstant. You can also get and set the
value of a field using the get and set methods. There is a general-purpose form of these methods that take
Object arguments and return Object values, and more specific forms that deal directly with primitive
types. All of these methods take an argument specifying which object to operate on. For static fields the object
is ignored and can be null. The following method prints the value of a short field of an object:
public static void printShortField(Object o, String name)
throws NoSuchFieldException, IllegalAccessException
{
Field field = o.getClass().getField(name);
short value = (Short) field.get(o);
System.out.println(value);
}
The return value of get is whatever object the field references or, if the field is a primitive type, a wrapper
object of the appropriate type. For our short field, get returns a Short object that contains the value of
the fieldthat value is automatically unboxed for storing in the local variable value.
The set method can be used in a similar way. A method to set a short field to a provided value might look
like this: