public final class ReflectTools extends Object
| Modifier and Type | Field and Description |
|---|---|
static int |
GETTER_INDEX |
static int |
SETTER_INDEX |
| Modifier and Type | Method and Description |
|---|---|
static Map<Field,Method[]> |
extractFieldsWithMethods(Class<?> type,
boolean ignoreSuperclasses)
Scans a class using reflection and associates fields with getters (first) and setters (second).
|
static Optional<Class<?>> |
extractGenericType(Field field,
int genericIndex)
Extracts the class present as the given parameter in the generic definition of the type in the given field.
|
static <V> Optional<V> |
getValueOfField(Object instance,
Class<? extends V> valueType,
String fieldName)
Attempts to get the value of a
Field of a given name that is declared in given class. |
static <T> T |
newInstance(Class<T> type)
Creates an instance of a given type through a publicly accessible no-arg constructor.
|
public static final int GETTER_INDEX
public static final int SETTER_INDEX
public static <V> Optional<V> getValueOfField(Object instance, Class<? extends V> valueType, String fieldName)
Field of a given name that is declared in given class. AccessibleObject.setAccessible(boolean) will be used.
This method will attempt to find a field in the class of the given object, and then it will go up the hierarchy until the field of given name and a compatible type is found.
When a field is found, an attempt to trySetAccessible will be made, followed by casting it to the provided value type.
When all the above is successful, an optional with the value of the field for the given object will be returned.V - Type of the returned object.instance - Instance of an object to get the field from.valueType - Type of value to expect from the field. Type of the field, if found, will be passed to this type's Class.isAssignableFrom(Class) for type checking.fieldName - Name of the field.Optional.empty().public static Map<Field,Method[]> extractFieldsWithMethods(Class<?> type, boolean ignoreSuperclasses)
public, non-static getters/setters in type, and returns those.
Setters must start with set, getters with get (is and are supported for booleans).
Return type of the getter must be the same as the field's type or one of its superclasses or superinterfaces.
The only parameter of the setter must either be the same type as the field's type or one of its subclasses.
Fields that have no setter and no getter are stripped from the result.
In case of duplicate names of fields only the first occurrence is kept.public static Optional<Class<?>> extractGenericType(Field field, int genericIndex)
List<String>, the generic type at index zero will be String.class.field - Field to check.genericIndex - Index of the type to return.public static <T> T newInstance(Class<T> type)
T - Type of object to create.type - Type to create.IllegalArgumentException - when the object cannot be created for any reasonCopyright © 2023 Miki. All rights reserved.