]> git.lizzy.rs Git - BoundingBoxOutlineReloaded.git/blob - src/main/java/com/irtimaled/bbor/common/ReflectionHelper.java
Fix bug in ReflectionHelper
[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 (!typesMatch(genericTypeArguments, actualTypeArguments)) continue;
37
38             return field;
39         }
40         return null;
41     }
42
43     private static boolean typesMatch(Type[] left, Type[] right) {
44         if (left.length != right.length) return false;
45
46         for (int index = 0; index < right.length; index++) {
47             if (right[index] != left[index]) {
48                 return false;
49             }
50         }
51         return true;
52     }
53 }