1 package com.irtimaled.bbor.common;
3 import java.lang.reflect.Field;
4 import java.lang.reflect.ParameterizedType;
5 import java.lang.reflect.Type;
6 import java.util.function.Function;
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;
13 field.setAccessible(true);
16 return (R) field.get(obj);
17 } catch (IllegalAccessException ignored) {
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;
32 Type rawType = genericType.getRawType();
33 if (rawType != fieldType) continue;
35 Type[] actualTypeArguments = genericType.getActualTypeArguments();
36 if (actualTypeArguments.length != genericTypeArguments.length) continue;
38 for (int typeIndex = 0; typeIndex < actualTypeArguments.length; typeIndex++) {
39 if (actualTypeArguments[typeIndex] != genericTypeArguments[typeIndex]) return null;