]> git.lizzy.rs Git - BoundingBoxOutlineReloaded.git/blob - src/main/java/com/irtimaled/bbor/common/ReflectionHelper.java
4ade3c2a4e7306b82c6c39156526cb623689bc32
[BoundingBoxOutlineReloaded.git] / src / main / java / com / irtimaled / bbor / common / ReflectionHelper.java
1 package com.irtimaled.bbor.common;
2
3 import java.lang.reflect.Field;
4 import java.lang.reflect.ParameterizedType;
5 import java.lang.reflect.Type;
6 import java.util.function.Function;
7
8 public class ReflectionHelper {
9     public static <T, R> Function<T, R> getPrivateFieldGetter(Class<?> clazz, Type fieldType, Type... genericTypeArguments) {
10         Field field = findField(clazz, fieldType, genericTypeArguments);
11         if (field == null) return obj -> null;
12
13         field.setAccessible(true);
14         return obj -> {
15             try {
16                 return (R) field.get(obj);
17             } catch (IllegalAccessException ignored) {
18                 return null;
19             }
20         };
21     }
22
23     private static Field findField(Class<?> clazz, Type fieldType, Type[] genericTypeArguments) {
24         for (Field field : clazz.getDeclaredFields()) {
25             Type type = field.getGenericType();
26             ParameterizedType genericType = TypeHelper.as(type, ParameterizedType.class);
27             if (genericType == null) {
28                 if (type != fieldType || genericTypeArguments.length > 0) continue;
29                 return field;
30             }
31
32             Type rawType = genericType.getRawType();
33             if (rawType != fieldType) continue;
34
35             Type[] actualTypeArguments = genericType.getActualTypeArguments();
36             if (actualTypeArguments.length != genericTypeArguments.length) continue;
37
38             for (int typeIndex = 0; typeIndex < actualTypeArguments.length; typeIndex++) {
39                 if (actualTypeArguments[typeIndex] != genericTypeArguments[typeIndex]) return null;
40             }
41
42             return field;
43         }
44         return null;
45     }
46 }