1 package com.irtimaled.bbor;
3 import com.irtimaled.bbor.common.TypeHelper;
5 import java.lang.reflect.Field;
6 import java.lang.reflect.ParameterizedType;
7 import java.lang.reflect.Type;
8 import java.util.function.Function;
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;
15 field.setAccessible(true);
18 return (R) field.get(obj);
19 } catch (IllegalAccessException ignored) {
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;
34 Type rawType = genericType.getRawType();
35 if (rawType != fieldType) continue;
37 Type[] actualTypeArguments = genericType.getActualTypeArguments();
38 if (actualTypeArguments.length != genericTypeArguments.length) continue;
40 for (int typeIndex = 0; typeIndex < actualTypeArguments.length; typeIndex++) {
41 if (actualTypeArguments[typeIndex] != genericTypeArguments[typeIndex]) return null;