Advertisement
bobmarley12345

reflect field accessor

Jan 28th, 2022
819
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. package reghzy.api.utils.reflect;
  2.  
  3. import reghzy.api.utils.text.RZFormats;
  4.  
  5. import java.lang.reflect.Field;
  6.  
  7. public class ReflectFieldAccessor<T, V> implements FieldAccessor<T, V> {
  8.     private final Field field;
  9.  
  10.     /**
  11.      * Crates a reflect field accessor that uses the given field!
  12.      */
  13.     public ReflectFieldAccessor(Field field) {
  14.         this.field = field;
  15.     }
  16.  
  17.     public static <T, V> ReflectFieldAccessor<T, V> create(Class<T> targetClass, Class<V> fieldType, String fieldName) {
  18.         Field field = Reflect.findPrivateField(targetClass, fieldName);
  19.         if (fieldType.isAssignableFrom(field.getType())) {
  20.             if (!field.isAccessible()) {
  21.                 field.setAccessible(true);
  22.             }
  23.  
  24.             return new ReflectFieldAccessor<T, V>(field);
  25.         }
  26.  
  27.         throw new RuntimeException(RZFormats.format("Incompatible field type. Field {0} cannot be assigned to {1}", field.getType().getName(), fieldType.getName()));
  28.     }
  29.  
  30.     /**
  31.      * Creates a field accessor that uses reflection to get/set the field
  32.      * <p>
  33.      *     This bypasses the field type checks that {@link ReflectFieldAccessor#create(Class, Class, String)}
  34.      *     does, therefore assuming the correct type is always passed
  35.      * </p>
  36.      * @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)
  37.      * @param fieldName Name of the field
  38.      * @param <T> Target class type
  39.      * @param <V> Field type
  40.      * @return A field accessor
  41.      */
  42.     public static <T, V> ReflectFieldAccessor<T, V> create(Class<T> targetClass, String fieldName) {
  43.         Field field = Reflect.findPrivateField(targetClass, fieldName);
  44.         if (!field.isAccessible()) {
  45.             field.setAccessible(true);
  46.         }
  47.  
  48.         return new ReflectFieldAccessor<T, V>(field);
  49.     }
  50.  
  51.     @Override
  52.     public V get(T target) {
  53.         return Reflect.getFieldValue(target, this.field);
  54.     }
  55.  
  56.     @Override
  57.     public void set(T target, V value) {
  58.         Reflect.setFieldValue(target, this.field, value);
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement