Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package reghzy.api.utils.reflect;
- import reghzy.api.utils.text.RZFormats;
- import java.lang.reflect.Field;
- public class ReflectFieldAccessor<T, V> implements FieldAccessor<T, V> {
- private final Field field;
- /**
- * Crates a reflect field accessor that uses the given field!
- */
- public ReflectFieldAccessor(Field field) {
- this.field = field;
- }
- public static <T, V> ReflectFieldAccessor<T, V> create(Class<T> targetClass, Class<V> fieldType, String fieldName) {
- Field field = Reflect.findPrivateField(targetClass, fieldName);
- if (fieldType.isAssignableFrom(field.getType())) {
- if (!field.isAccessible()) {
- field.setAccessible(true);
- }
- return new ReflectFieldAccessor<T, V>(field);
- }
- throw new RuntimeException(RZFormats.format("Incompatible field type. Field {0} cannot be assigned to {1}", field.getType().getName(), fieldType.getName()));
- }
- /**
- * Creates a field accessor that uses reflection to get/set the field
- * <p>
- * This bypasses the field type checks that {@link ReflectFieldAccessor#create(Class, Class, String)}
- * does, therefore assuming the correct type is always passed
- * </p>
- * @param targetClass The class in which the given field is stored in (can be a derived class, where the field is stored in a super class)
- * @param fieldName Name of the field
- * @param <T> Target class type
- * @param <V> Field type
- * @return A field accessor
- */
- public static <T, V> ReflectFieldAccessor<T, V> create(Class<T> targetClass, String fieldName) {
- Field field = Reflect.findPrivateField(targetClass, fieldName);
- if (!field.isAccessible()) {
- field.setAccessible(true);
- }
- return new ReflectFieldAccessor<T, V>(field);
- }
- @Override
- public V get(T target) {
- return Reflect.getFieldValue(target, this.field);
- }
- @Override
- public void set(T target, V value) {
- Reflect.setFieldValue(target, this.field, value);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement