Class FieldHandle<T>
- Type Parameters:
T
- the type of the field being accessed
This class provides a convenient way to access private, protected, or package-private fields using Java reflection. It automatically handles the accessibility setup and provides type-safe operations for getting and setting field values.
The field handle is created once with the field name and target class, after which
it can be used multiple times to access the field on different instances of that class.
The underlying Field
is made accessible during construction.
Example usage:
// Create a handle for a private field
FieldHandle<String> nameHandle = new FieldHandle<>("name", SomeClass.class);
// Get the field value from an instance
SomeClass instance = new SomeClass();
String name = nameHandle.get(instance);
// Set a new field value
nameHandle.set(instance, "New Name");
-
Constructor Summary
ConstructorsConstructorDescriptionFieldHandle
(String fieldName, Class<?> clazz) Creates a new field handle for the specified field in the given class. -
Method Summary
-
Constructor Details
-
FieldHandle
Creates a new field handle for the specified field in the given class.This constructor uses reflection to locate the field by name and makes it accessible for future operations. If the field cannot be found, a
RuntimeException
is thrown.- Parameters:
fieldName
- the name of the field to accessclazz
- theClass
containing the field- Throws:
RuntimeException
- if the field cannot be found in the specified class
-
-
Method Details
-
set
Sets the value of the field on the specified object instance.This method uses reflection to set the field value on the provided object. The value is set directly without any type checking beyond what the underlying reflection API provides.
- Parameters:
object
- the object instance to modify (must be an instance of the class used in construction)value
- the value to set in the field- Throws:
RuntimeException
- if the field value cannot be set due to access restrictions or other reflection issues
-
get
Retrieves the value of the field from the specified object instance.This method uses reflection to get the field value from the provided object. The returned value is cast to the generic type
T
for type safety.Note: The type cast is unchecked and relies on the caller to ensure the generic type parameter matches the actual field type.
- Parameters:
object
- the object instance to read from (must be an instance of the class used in construction)- Returns:
- the current value of the field, cast to type
T
- Throws:
RuntimeException
- if the field value cannot be retrieved due to access restrictions or other reflection issues
-