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